Python语法基础:文件操作

文件

一.打开文件

在python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件

open(文件名,访问模式)

示例:f=open(‘test.txt’,‘w’)

访问模式:

二.关闭文件

close()

示例:f.close()

三.文件的读写(write)

1).写数据(write)

f = open('test.txt', 'w')

f.write('hello world, i am here!')

f.close()

注意如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

2).读数据(read)

使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据

 
f=open("test.txt","r")
content=f.read(5)
print(content)
print("-"*30)
content=f.read()
print(content)
f.close()
 

注意:

  • 如果open是打开一个文件,那么可以不用谢打开的模式,即只写 open('test.txt')
  • 如果使用读了多次,那么后面读取的数据是从上次读完后的位置开始的

3).读数据(readlines)

就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素

f=open("test.txt",'r')
content=f.readlines()
print(type(content))
for temp in content:
    print(temp)
f.close()

4).读数据(readline)

只读取一行

f=open("test.txt",'r')
content=f.readline()
print(content)
f.close()

 四.制作文件备份

oldFileName=input("请输入要拷贝的文件名字:")
oldFile = open(oldFileName,'r')
# 如果打开文件
if oldFile:
    # 提取文件的后缀
    fileFlagNum = oldFileName.rfind('.')
    if fileFlagNum > 0:
        fileFlag = oldFileName[fileFlagNum:]
    # 组织新的文件名字
    newFileName = oldFileName[:fileFlagNum] + '[复件]' + fileFlag
    # 创建新文件
    newFile = open(newFileName, 'w')
    # 把旧文件中的数据,一行一行的进行复制到新文件中
    for lineContent in oldFile.readlines():
        newFile.write(lineContent)
    # 关闭文件
    oldFile.close()
    newFile.close()

五.文件的定位读写

<1>获取文件当前读写的位置

在读写文件的过程中,如果想知道当前的位置,可以使用tell()来获取

f=open("test.txt",'r')
str=f.read(3)
print("读取的数据为:",str)
position=f.tell()
print("当前文件的位置:",position)
str=f.read(3)
print("读取的数据为:",str)
position=f.tell()
print("当前文件的位置:",position)
f.close()

<2>定位到某个位置

如果在读写文件的过程中,需要从另外一个位置进行操作的话,可以使用seek()

seek(offset, from)有2个参数:

offset:偏移量                                               

 from:方向——0:表示文件开头

                        1:表示当前位置

                        2:表示文件末尾

f=open('test.txt','r')
str=f.read(30)
print("读取的数据是:",str)
position=f.tell()
print("当前文件的位置:",position)
f.seek(5,0)
position=f.tell()
print("当前文件位置:",position)
f.close()

六.文件的重命名、删除

1).文件重命名

import os
os.rename("test.txt","testdwx.txt")

2).删除文件

import os
os.remove('test[复件].txt')

七.文件夹的相关操作

就像对文件操作需要os模块一样,如果要操作文件夹,同样需要os模块

1).创建文件夹

import os
os.mkdir("邓文雄")

2).获取当前目录

import os
print(os.getcwd())

3).改变默认目录

import os
os.chdir("../")
os.mkdir("xiong")#会在默认路径的上一级创建文件夹“xiong”

4).获取目录列表

import os
print(os.listdir("./"))

5).删除文件夹

import os
os.chdir('../')
os.rmdir('xiong')

猜你喜欢

转载自www.cnblogs.com/python-road/p/10486073.html