文件操作
在python中读写文件有3个步骤
- 调用
open()函数,返回一个File对象。1
helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt')
调用File对象的
read()或write()方法。1
2helloFile.read()
'Hello World!\n这是一个测试文件读写的文档!'调用File对象的
close()方法关闭该文件。1
helloFile.close()
open()函数打开文件
open() 函数常用参数
第一个参数是文件,使用open()函数打开一个文件,首先要给它传递一个字符串路径表示要打开的文件。这里既可以是绝对路径,也可以是相对路径。
第二个参数是文件打开模式,默认为rt。常用模式如下r 只读模式打开文件,默认。w 读模式打开文件,用于向文件写入。若文件不存在则自动创建,若存在则会覆盖原文件从头开始写。x 创建一个新文件然后向文件写入。a 追加,用于向文件写入。若文件存在则从文件末尾开始继续添加,不会覆盖原文件。b 二进制模式。返回的文件内容为未解码的bytes对象。t 文本模式,默认模式。返回的文件内容为stings。也就是bytes对象经过系统默认编码(或指定的编码格式)使用decode()转换之后返回。open()函数返回值为File对象。当需要读取或者写入的时候直接调用该对象的方法即可。
示例
读模式打开文件
方法11
helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt')
方法21
helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt', 'r')
上面2种方法是一致的,因为默认情况下就是使用r模式打开文件。
读取文件内容
上面已经创建了一个File对象,下面可以进行读取。
常用读取方法有3种read() 读取整个文件,返回内容为strings。readline() 按行读取文件,调用一次读取一行。readlines() 读取整个文件按行返回到list中。
示例
使用read()方法1
2
3
4
5helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt')
helloCentent = helloFile.read()
helloCentent
helloFile.close()
'Hello World!\n这是一个测试文件读写的文档!'
使用readline()方法1
2
3
4
5
6
7
8
9helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt')
helloCentent = helloFile.readline() #读取第一行
helloCentent
'Hello World!\n'
helloCentent = helloFile.readline() #读取第二行
helloCentent
'这是一个测试文件读写的文档!'
helloCentent = helloFile.readline() #后面再没有内容
helloFile.close()
使用readlines()方法1
2
3
4
5helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt')
helloCentent = helloFile.readlines()
helloCentent
['Hello World!\n', '这是一个测试文件读写的文档!']
helloFile.close()
扩展:readlines()方法得到的列表如何操作?如何得到行号?1
2
3
4
5
6
7helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt')
helloContet = helloFile.readlines()
for i, content in enumerate(helloContet):
print("第{0}行内容是:{1}".format(i, content), end="")
...
第0行内容是:Hello World!
第1行内容是:这是一个测试文件读写的文档!
写入文件
要在文件中写入内容,需要以w或a模式打开文件,若open()打开的文件不存在,将会创建新的空白文件。写入之后需要使用close()方法关闭。
示例
使用w(写)模式写入1
2
3
4
5
6
7
8
9
10baconFile = open('bacon.txt', 'w') #该文件此时不存在
baconFile.write('Hello World!\n') #写入时若需要换行符需要自己添加
13 #返回的为写入字符的个数
baconFile.write('正在测试写模式写入!\n')
11
baconFile.close()
baconFile = open('bacon.txt')
baconFile.read() #再次读取,已经正确写入
'Hello World!\n正在测试写模式写入!\n'
baconFile.close()
使用a(追加)模式写入1
2
3
4
5
6
7
8baconFile = open('bacon.txt', 'a')
baconFile.write('正在测试追加模式写入!\n')
12
baconFile.close()
baconFile = open('bacon.txt')
baconFile.read()
'Hello World!\n正在测试写模式写入!\n正在测试追加模式写入!\n'
baconFile.close()
需要特别注意w模式,假如写入的文件已存在,将会覆盖原文件,从头写入。
使用with
从上面代码看到,每次调用open()打开文件,调用write()写入文件,总是要调用close()关闭文件。这样比较麻烦,python引入with语句自动帮我们调用close()方法。1
2
3
4
5
6with open('bacon.txt', 'r') as f:
print(f.read())
...
Hello World!
正在测试写模式写入!
正在测试追加模式写入!
当我们写入文件时,操作系统往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘。忘记调用close()后果是数据可能只写了一部分到磁盘造成数据丢失。建议操作文件IO时始终使用with语句。
其他文件对象方法
name 返回该对象对应的文件名1
2
3
4with open('bacon.txt', 'r') as f:
print(f.name)
...
bacon.txt
fileno() 返回文件描述符
文件描述符是非负整数,内核访问文件的时候使用文件描述符,以此指定操作的文件。具体的使用办法以后再说。1
2
3
4with open('bacon.txt', 'r') as f:
print(f.fileno())
...
5
encoding() 返回文件编码1
2
3
4with open('bacon.txt', 'r') as f:
print(f.encoding)
...
cp936 #此处cp936就是GBK编码
closed 返回值为布尔值,判断文件是否已经关闭。1
2
3
4
5
6baconFile = open('bacon.txt')
baconFile.closed #打开之后尚未关闭
False
baconFile.close()
baconFile.closed #已经使用close()方法关闭
True
tell() 返回文件当前位置
seek(offset, whence) 设置文件当前位置
offset 表示偏移量,正数向后偏移,负数向前偏移
whence 0表示文件开头 1表示现在位置 2表示文件末尾1
2
3
4
5
6
7
8
9
10
11
12
13
14
15f = open('sunny.txt', 'r', encoding='utf-8') #文件内容
f.read()
'Hello World!\n正在测试seek功能!\n正在测试truncate功能!\n'
f.close()
f = open('sunny.txt', 'rb')
f.tell()
0
f.readline()
b'Hello World!\r\n'
f.tell()
14
f.seek(3,1)
17
f.tell()
17
注意:当使用上述方法时建议使用b模式打开文件。
truncate(size)
从文件首行首字符开始截断,截断文件为size个字符,无size表示从当前位置开始截断。截断之后后面的所有字符均删除。windows下换行符代表2个字符。
原始文件内容
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
使用下面语句截取1
2
3helloFile = open('D:\\BaiduNetdiskDownload\\livepython1\\06\\file.txt', 'r+', encoding='utf-8')
helloFile.truncate(12)
helloFile.close()
输出结果
This is 1st
包括1st后面的空格,一共为12个字符。
文件编码
关于python中文件编码的具体说明可参照前面的文章python编码,此处主要针对open()方法的encoding参数。
要写入特定编码的文本文件,给open()函数传入encoding参数,将字符串转换成指定编码。1
2
3
4
5
6
7
8
9
10
11
12
13
14with open('bacon.txt', 'r', encoding='gbk') as f: #根据上面encoding方法返回结果可知该文件为GBK编码
print(f.read()) #指定使用GBK编码可正常输出
...
Hello World!
正在测试写模式写入!
正在测试追加模式写入!
with open('bacon.txt', 'r', encoding='UTF-8') as f: #当使用utf-8编码输出时就会报错
print(f.read())
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Users\xiaohuihui\AppData\Local\Programs\Python\Python36\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 14: invalid continuation byte