Python读写文件操作


读写文件

Python有一些内置函数(如open)来读取和写入文件的信息。

Open函数

open函数功能是用来打开一个文件,可以进行读操作和写操作,通过设置函数第二个参数的值来设定文件的访问方式:

  • r表示以读取模式打开
  • rb表示读取二进制文件
  • w表示以写入模式打开
  • wb表示写入二进制文件
  • a表示以追加模式打开。

open函数返回的对象是文件对象,在使用过后记得关闭(close)。

读取文件

通过设置open函数的第二个参数为r,来进行读取文件:

1
2
3
4
# 打开一个文件
f = open("input.txt", "r")
# 关闭文件
f.close()

input.txt内容为:

1
2
I am a temporary file.
Maybe someday, I'll become a real file.

由于IO操作可能会产生IOError,所以我们可以将close操作放在finally里面:

1
2
3
4
5
try:
f = open("input.txt", "r")
finally:
if f:
f.close()

Python引入了with语句来自动帮我们调用close()方法

1
2
with open("input.txt", "r") as f:
print(f.read())

read()

调用该方法可以一次读取文件的全部内容,当然如果你一个文件过大的话,可以反复调用read(size)方法,每次最多读取size个字节的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
f = open("input.txt", "r")
# 读取全部内容
print(f.read())
"""
print:

I am a temporary file.
Maybe someday, I'll become a real file.
"""
# 读取部分内容
print(f.read(32))
"""
print:

I am a temporary file.
Maybe som
"""
f.close()

readline()

调用该方法可以每次读取一行文件的内容:

1
2
3
4
5
6
7
8
9

with open("input.txt", "r") as f:
print(f.readline())

"""
print:

I am a temporary file.
"""

reallines()

调用该方法可以一次读取所有内容并按行返回个数组:

1
2
3
4
5
6
7
8
9
10
11
12

with open("input.txt", "r") as f:
for line in f.readlines():
print(line)

"""
print:
I am a temporary file.

Maybe someday, I'll become a real file.

"""

写入文件

通过设置open函数的第二个参数为w或者a,来进行写入文件。

  • w是写入,如果该文件不存在则先创建该文件,再写入,如果已存在该文件,则先删除,再创建,然后写入。
  • a是追加,如果该文件不存在则先创建该文件,再写入,如果已存在该文件,则在文件后面追加写入。

由于当我们写文件时,不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。只有调用close()方法后,才会将数据全部写入磁盘。

write()

所以使用with语句,确保及时写入数据:

1
2
3

with open("output.txt", "r") as f:
f.write("write\n")

其中,output.txt内容为:

1
This is output file.

writelines()

写入文件同样可以将数组写进文件:

1
2
3

with open("output.txt", "r") as f:
f.writelines(["1\n", "2\n", "3\n"])

最后文件内容:

1
2
3
4
5
This is output file.
write
1
2
3

读写二进制文件

通过设置open函数的第二个参数为rb或者wb,来进行读写二进制文件,如图片,视频等等,读取的内容都是十六进制表示的字节。

读取一张图片:

1
2
3
4

with open("timg.jpg", "rb") as f:
for line in f.readlines():
print(line)

打印的内容为(省略了一些):

1
2
3
4
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xdb\x00C\x00\t\x06\x07\x08\x07\x06\t\x08\x07\x08\n'
b'\n'
b'\t\x0b\r
...

字符编码

一般文件的编码都是UTF-8,但是如果是其他编码的文件,那么需要在open函数的第三个参数设置encoding编码类型:

1
2
3
4
5
# gbkTxt.txt 内容为 测试
with open("gbkTxt.txt", "r", encoding="gbk") as f:
print(f.read())

# print 测试

如果一个文件里面的存在非法编码的字符,那么就会产生UnicodeDecodeError,如何处理这种情况呢?

open函数提供了一个errors参数,来进行遇到编码错误后的处理,最简单的方式是直接忽略:

1
2
with open('test.txt', 'r', encoding='gbk', errors='ignore') as f:
...

总结

Python进行文件读写操作还是很方便的,最主要的就是要记住打开文件后,要记得关闭文件操作close,通常使用with操作来自动关闭;在遇到编码不一样的时候要设置对应的编码,同时可以忽略编码错误的操作,读取二进制文件的操作也是很简单。