文件操作

f = open('文件名',mode='',encoding='utf-8')      open 打开

第一个内容是文件的名字,必须是字符串;

第二个内容是对这个文件的操作方式;

第三个是这个文件的编码集;

f 文件句柄 所有对文件的操作都是操作文件句柄.

content = f.read()            一次性读取全部,read里的参数就是表示读取的字符数量,read(3)就是读取3个字符

content = f.readline()      读取一行 尾部有
换行

content = f.readlines()    一行一行 读取多行,存放在列表里

mode(模式)   常用的有如下几种:

r:

f = open('文件名',mode='r',encoding='utf-8')

mode = r   只读

rb:

f = open('文件名',mode='rb')

mode = 'rb' 读取字节 不能指定编码集    read(3)就是读取3个字节

w:

f = open('t1.txt',mode='w',encoding='utf-8')

f.write('')

w模式 如果文件不存在 就新建一个 ,覆盖写,写之前先把文件清空

只写 没有读的功能

a:

f = open('t1',mode='a',encoding='utf-8')

'a'模式 追加,在文件最后添加内容

r+:

f = open('t1',mode='r+',encoding='utf-8')

r+   先读后写

w+:

f = open('t1',mode='w+',encoding='utf-8')

f.write('周一')

f.seek(0)         

print(f.read())

#先写后读 需要用seek移动光标到最前面再读取

a+:

f = open('t1',mode='a+',encoding='utf-8')

f.seek(0)

print(f.read())

f.write('周一')

#同样是先写后读,相比于write,a+为追加写,write为覆盖写,更推荐a+的用法

其他操作:

tell      查看光标位置,数的是字节

with open('t1','r',encoding='utf-8')as f:
print(f.read())
print(f.tell()) 

seek    移动光标

双数字:

seek(0,0)    移动到文件头部

seek(0,1)    移动到当前位置

seek(0,2)    移动到文件尾部

单数字:

seek(3)     数字表示字节

f.truncate()     截取 指定光标位置 按字节算数

with open('t1','r',encoding='utf-8')as f:

f.truncate(9) 截取9个字节,也就是3个字符,在python3中,要先手动移动光标,再截取

flush     刷新

os.rename('旧的名字','新的名字')      重命名

os.remove('删除的文件')                    删除文件

with open     上下文管理

with open('t1',mode='r',encoding='utf-8')as f:
msg = f.read()
print(msg)

不用手动关闭文件,操作完之后自动关闭文件

绝对路径和相对路径

从磁盘开始查找的就是绝对路径    Cusers.....

相对于某个文件位置来查找的一种路径 

一般推荐写相对路径

文件修改
先做备份

with open('原文件',mode='',encoding = '编码集')as f,

open('新文件',mode='',encoding='编码集')as f1:

f 原文件的句柄

f1 新文件的句柄

msg = f.read() 读取原文件内容,临时存到msg变量中

s = msg.repleace('被修改的内容','修改后的内容')

f1.write(s) 将修改的内容写到新文件中 原文件不动

按照上边的写法,有时会出现一些弊端,文件太大的时候 内存容易溢出,需要用for循环:

with open('原文件',mode='',encoding = '编码集')as f,

open('新文件',mode='a+',encoding='编码集')as f1:

for i in f:                 #一行一行读取

msg = i.strip().repleace('','')

f1.write(msg)

原文地址:https://www.cnblogs.com/sandy-123/p/10239233.html