Python读写文件时非常流行的操作。Python读文件有3种方法:read()、readline()和readlines()。Python写文件有2种方法:write()和writelines()。
可以先编辑一下文件并写入一些信息。在文本文件“example.txt”中写入如下内容:
- "Whenever you feel like criticizing anyone,"
- he told me,
- “just remember that all the people in this world
- haven’t had the advantages that you’ve had.
1、读取文件
文件对象的read()方法用于读取文件,当不传递任何参数时,read()方法将读取整个文件:
- >>> with open('example.txt', 'r') as f: # 使用r模式
- ... print(f.read()) # 将读取内容打印出来
- ...
- "Whenever you feel like criticizing anyone,"
- he told me,
- “just remember that all the people in this world
- haven’t had the advantages that you’ve had.
read()方法也可以通过传递参数来指定读取的字节数:
- >>> with open('example.txt', 'r') as f:
- ... print(f.read(8)) # 读取8个字节的数据
- ...
- "Wheneve
readline()方法用于读取整行文本:
- >>> with open('example.txt', 'r') as f:
- ... print(f.readline()) # 仅读取第一行
- ...
- "Whenever you feel like criticizing anyone,"
- >>> with open('example.txt', 'r') as f:
- ... for _ in range(3): # 读取前三行文本
- ... print(f.readline())
- ...
- "Whenever you feel like criticizing anyone,"
- he told me,
- “just remember that all the people in this world
readline()方法同样可以通过传递参数来指定读取的字节数:
- >>> with open('example.txt', 'r') as f:
- ... for _ in range(3):
- ... print(f.readline(6))
- ...
- "Whene
- ver yo
- u feel
readlines()方法用于读取文件对象剩余的全部行,以列表的形式返回:
- >>> with open('example.txt', 'r') as f:
- ... print(f.readlines())
- ...
- ['"Whenever you feel like criticizing anyone," \n', 'he told me, \n', '“just remember that all the people in this world \n', 'haven’t had the advantages that you’ve had.']
- >>> with open('example.txt', 'r') as f:
- ... print(f.readline()) # 先使用readline()读取一行
- ... print(f.readlines()) # 再使用readlines()读取剩余的全部行
- ...
- "Whenever you feel like criticizing anyone,"
- ['he told me, \n', '“just remember that all the people in this world \n', 'haven’t had the advantages that you’ve had.']
2、写入文件
使用Python写入文件时,需要以写“w”或附加“a”模式打开文件。需要谨慎使用“w”模式,因为它会覆盖文件(如果文件已存在),该文件之前的所有数据都将被删除。写入字符串或字节序列(对于二进制文件)是使用write()方法实现的,返回写入文件的字符数:
- >>> with open('example.txt', 'w') as f: # 使用'w'模式
- ... f.write('I love Python')
- ... f.write('Hello!')
- ...
- 13
- 6
打开文本文件“example.txt”,会发现文件中的内容已被覆盖了,原先的所有数据都被删除了,此时文件中的内容是刚刚使用write()方法写入的。
writelines()方法用于一次性写入多行文件:
- >>> with open('example.txt', 'a') as f: # 使用'a'追加模式
- ... f.writelines(['Over and Over', 'DealBreaker'])
- ...
再次打开文本文件“example.txt”,会发现文件中原先的数据没有被删除,使用write()方法写入的数据被追加到了原数据的末尾。