python文件,字符串,二进制的读写

读文件:

f = open('/Users/michael/test.txt', 'r')
#一次读取文件的全部内容
f.read()
#文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的
close()
#考虑异常,无论是否出错都能正确地关闭文件
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
#等价于 with语句来自动帮我们调用close()方法 
with open('/path/to/file', 'r') as f:
print(f.read())

#二进制文件
 f = open('/Users/michael/test.jpg', 'rb')

#字符编码
#要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')

#遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,直接忽略
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore'

写文件:
#传入标识符'w'或者'wb'表示写文本文件或写二进制文件
f = open('/Users/michael/test.txt', 'w')
f.write('Hello, world!')
f.close()

#要写入特定编码的文本文件,请给open()函数传入encoding参数
with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')

最好使用with语句

StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口

StringIO和BytesIO

str的读取:

#写入字符串
from io import StringIO
f = StringIO()
f.write(''Hello!
Hi!
Goodbye!'')  

#getvalue()方法用于获得写入后的str
print(f.getvalue())
#或者行读
while True:
    s = f.readline()
    if s == '':
         break
    print(s.strip())
#结果
Hello!
Hi!
Goodbye!

二进制的读取:

from io import BytesIO
#
f = BytesIO()
#经过UTF-8编码的bytes
f.write('中文'.encode('utf-8'))
print(f.getvalue())
#结果
b'xe4xb8xadxe6x96x87

#
f = BytesIO(b'xe4xb8xadxe6x96x87')
f.read()
#结果
b'xe4xb8xadxe6x96x87'