Python学习笔记(12), 文件读写

文件读写

文件读写的本质是调用操作系统的system interface。

读文件

以读文件的模式打开一个文件对象

f = open('../module_test/hello.py', 'r')   # 以读的方式打开一个文件
f.read()  # 一次读取文件的全部内容到内存,用一个str对象表示
'print("in hello.py module")\n\nif __name__ == \'__main__\':\n    print(\'in the __main__\')'
f.close()  # 关闭文件

由于文件读写可能产生IOError,可以使用try...except...finally打开文件

try:
    f = open('../module_test/hello2.py', 'r')
    print(f.read())
except IOError as e:
    print(e)
finally:
    if f:
        f.close()
[Errno 2] No such file or directory: '../module_test/hello2.py'

Python为了简洁,引入with来自动帮我们调用close()方法:

with open('../module_test/hello.py', 'r') as f:
    print(f.read())
print("in hello.py module")

if __name__ == '__main__':
    print('in the __main__')

一些其他的读文件方法:

  • read(size), 每次最多读取size个字节的内容
  • readline(), 每次读取一行的内容
  • readlines(), 一次读取所有内容并按行返回list

file-like Object

open()函数返回的这种有个read()方法的对象,在Python中统称为file-like Object。除了file外,还可以是内存的字节流,网络流,自定义流等等。file-like Object不要求从特定类继承,只要写个read()方法就行。

StringIO就是内存中创建的file-like Object, 常用作临时缓冲。

二进制文件读取以'rb'模式打开文件,open('/filename', 'rb')
读取非UTF-8编码的文本文件,给open()加上encoding=参数即可。
f = open('/filename', 'r', encoding='gbk', errors='ignore')

写文件

调用open()时,传入标识符'w'或者'wb'表示写文件, The mode can be 'r', 'w', 'x' or 'a' for reading (default), writing, exclusive creation or appending.

f = open('./test.txt', 'a')
f.write('Hello world')
f.close()
with open('./test.txt', 'w') as f:
    f.write('Hello world!')

所有模式的定义可参考https://docs.python.org/3/library/functions.html#open

StringIO和BytesIO

数据读写不一定是在文件中,也可以内存中读写,StringIO和BytesIO是在内存中操作strbytes的方法,使得和读写文件具有一致的接口

先创建一个StringIO,像文件一样写入

from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
hello world!

读取StringIO, 用str初始化StringIO,然后像文件一样读取, BytesIO同理。

from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip())
Hello!
Hi!
Goodbye!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值