文件操作:
首先要有一个文件作为对象,例‘文件名’.txt
1.文件路径:例 d:\文件名.txt
<1>:绝对路径:从根目录往后的路径
<2>:相对路径:当前目录下的路径有什么算什么
2.编码方式:UTF-8、GBK2312等
3.操作模式:只读、只写、追加、写读、读写等
文件是以什么变法方式储存就要以什么编码方式打开
f = open('目标文件',mode='r',encoding='utf-8') #以UTF-8编码的文件为例 content = f.read() print(content) f.close()
读:
1.mode = 'r'文件的默认读取方式
f.read() 文件打开后将bytes类型转化为str类型,返回值是str,Python3下的编码方式是unicode,
f2 = open('f:\目标文件.txt',mode='r',encoding='gbk') #打开的文件编码是gbk content2 = f2.read() print(content2) #asd123文件 f2.close()
2.mode = 'rb'主要用于非文字类型文件操作,不用写编码方式
3.先读后写
f = open('目标文件',mode='r+',encoding='utf-8') print(f.read()) #123456789 f.write('abcd123') f.close() #123456789abcd123
在f.write()后添加一个print(f.read()) ,这段代码并不会执行
在r+模式下进行写读,写了多少就会覆盖多少
#原文件内容:123456789 f = open('目标文件',mode='r+',encoding='utf-8') f.write('abcdefg') print(f.read()) #89 f.close()
4.mode = 'r+b' 以bytes类型打开
#原文件内容:123456789 f = open('目标文件',mode='r+b') print(f.read()) #b'123456789' f.write('abc'.encode('utf-8')) f.close() #文件更新后:123456789abc 以utf-8编码
写:
在写入一个文件时若没有就会创建一个新的文件,有则将原文件删除再添加新的文件
1.只读 mode = 'w'
#原文件内容:123456789 f = open('目标文件',mode='w',encoding='utf-8') f.write('abcdefg') f.close() #文件更新后:abcdefg
2.mode = 'wb'
#原文件内容:123abc中国 f = open('目标文件',mode='wb') f.write('gbka123'.encode('utf-8')) f.close() #文件更新后:gbka123 编码方式:utf-8
如果再以gbk编码方式去读取这个文件那么将报错
3.mode = 'w+' 先写后读
#原文件内容:123abc中国 f = open('目标文件',mode='w+',encoding='utf-8') f.write('gbk2312') print(f.read()) f.close() #文件更新后:gbk2312 编码方式:utf-8
4.mode = 'w+b'
f1 = open('logo-grey.png',mode='rb') content = f1.read() print(content) f1.close() f2 = open('logo-grey2.png',mode='wb') f2.write(content) f2.close()
将原文件以rb形式读出来再写入到一个新的文件中去
追加:
1.mode = 'a'
#原文件内容:123abc中国 f = open('目标文件',mode='a',encoding='utf-8') f.write('%%%%') f.close() #文件更新后:123abc中国%%%% 编码方式:utf-8
2.mdoe = 'a+'
#原文件内容:123abc中国 f = open('目标文件',mode='a+',encoding='utf-8') f.write('%%%%') print(f.read()) f.close() #文件更新后:123abc中国%%%% 编码方式:utf-8
其他功能:
1.f.read(n)
当文件打开的方式为文本模式时,代表读取n个字符
#原文件内容:123abc中国 f = open('目标文件',mode='r',encoding='utf-8') content = f.read(6) print(content) f.close() #123abc
当文件打开为b模式时,代表读取n个字节
f = open('logo-grey.png',mode='rb') content = f.read(10) print(content) f.close() #b'\x89PNG\r\n\x1a\n\x00\x00'
2.f.seek(光标位置)
seek(n)光标移动到n位置,移动的单位为byte,所有utf-8编码的中文部分必须是3的倍数
移动到开头:seek(0)
移动到结尾:seek(0,2) seek最后一个参数表示从哪个位置进行偏移,1表示前位置,2表示结尾
#原文件内容:123abc中国 f = open('目标文件',mode='r+',encoding='utf-8') f.seek(0) #将光标置于开头 print(f.read()) f.seek(0) #将光标置于开头 f.seek(0,2) #将光标置于结尾 print(f.read()) #读到空白 f.seek(0) f.write('随便') f.flush() #文件更新后:随便中国 3*2 = 6 byte f.close()
3.f.tell()
告诉我们光标在什么位置
#原文件内容:123abc中国 f = open('目标文件',mode='r+',encoding='utf-8') f.seek(0) #将光标置于开头 print(f.tell()) #0 print(f.read()) f.seek(0) #将光标置于开头 print(f.tell()) #0 f.seek(0,2) #将光标置于结尾 print(f.tell()) #12 print(f.read()) #读到空白 f.seek(0) print(f.tell()) f.write('随便') f.flush() #文件更新后:随便中国 3*2 = 6 byte print(f.tell()) #6 f.close()
4.f.readable()&f.writeable() 判断是否可读
#原文件内容:123abc中国 f = open('目标文件',mode='r+',encoding