IO编程

来源:互联网 发布:电视机的电视直播软件 编辑:程序博客网 时间:2024/05/24 06:01

读文件

f = open('xxx/xx/x.text', 'r')

r表示读。.text表示读取文本文件。
文件不存在的话,就会跑出一个IOError错误。
文件成功打开,调用read().

f.read()

文件使用完后要关闭。

f.close()

二进制文件
如图片,视频等等,用’rb’模式打开。

f = open('xxx/xx/x.ipg', 'rb')

字符编码
读取非UTF-8编码的文本文件,传入encoding=’gbk’参数。

f = open('xxx/xx/x.text', encoding = 'gbk')

还可以加入errors参数,直接忽略错误的编码。
errors=’ignore’

写文件

f = open('xxx/xx/x.text', 'w')   打开可写文件f.write('hello,world!')  #写入文件f.close()   #关闭文件

with语句
自动跳动close()方法。

#打开之后会自动关闭with open('/path/to/file', 'r') as f:    print(f.read())

with…as…机制是参考了try…except…finally.

StringIO
将str写入StringIO,先创建一个StringIO,再用getvalue()方法用于获得写入后的str。

>>> from io import StringIO>>> f = StringIO()>>> f.write('hello')5
>>> print(f.getvalue())hello world!
原创粉丝点击