读:read(), read(size), readlines()
写:write()
关闭 close()
StingIO, BytesIO()
读文本文件
read()
f = open('D:/test.txt', 'r') # 'r'表示读文件
f.read() #调用read()方法一次性读取文件的内容
f.close() #关闭文件
通过with方法,不用关闭文件,执行完毕自动关闭
with open('D:/test.txt', 'r') as f:
print(f.read())
with open('D:/test.txt', 'r')as f:
for line in f.readlines():
print(line)
读取二进制文件,比如图片,视频,要用‘rb’模式打开
with open('C:/Users/Public/Pictures/Sample Pictures/aa.jpg', 'rb') as f:
print(f.read(100))
读取非UTF-8编码的文件,在open方法里加上参数encoding = ''
如读取GBK编码的文件:
with open('C:/Users/Public/Pictures/Sample Pictures/gbk.jpg', 'r', encoding = 'GBK') as f:
print(f.read(100))
写文件write()
注意注意:这种写法会把文件里原来的内容删除
with open('D:/test.txt', 'w') as f:
f.write('test write')
在文件里添加内容的写法是:传入参数‘a’代替‘w’
with open('D:/test.txt', 'a') as f:
f.write('test write')
StringIO就是内存中读写str
用write()方法写入,然后必须用getvalue()方法读取
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world')
print(f.getvalue())
BytesIO用来操作二进制数据
f = BytesIO()
f.write('刘数量'.encode('utf-8'))
print(f.getvalue())
f = BytesIO(b'xe5x88x98xe8x8bxb1')
print(f.read())