读文件 ‘r’
f = open('/Users/michael/test.txt', 'r')
>>> f.read()
>>> f.close()
with open('/Users/michael/test.txt', 'w') as f:
写文件 'w'
with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')
二进制文件 'rb'
f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六进制表示的字节
字符编码 encoding
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
>>> f.read()
'测试'
read() &readline() &readlines()
read() 会一次性读取文件的全部内容。可以反复调用read(size)方法,每次最多读取size个字节的内容。
readline() 可以每次读取一行内容
readlines() 一次读取所有内容并按行返回list
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉