7.1 文件 I/O
文件(file)用于长期保存数据。程序运行结束后,内存(memory)中的变量会消失,但写入文件的数据可以保留下来。文件 I/O(input/output)就是“从文件输入数据”和“向文件输出数据”。
open()
操作文件前,需要先用 open() 打开文件。open() 返回一个文件对象,后续读取、写入、关闭都通过这个对象完成。
python
file = open("text.txt", "r", encoding="UTF-8")
content = file.read()
file.close()常见打开模式:
r:只读,文件必须存在。w:只写,会创建新文件;如果文件已存在,会覆盖原内容。a:追加写入,内容会写到文件末尾。r+:读写,文件必须存在。
更推荐使用 with open(...) as file,因为 with 语句(with statement)会在代码块结束后自动关闭文件。
python
with open("text.txt", "r", encoding="UTF-8") as file:
content = file.read()注意
读文件时通常要写
encoding="UTF-8"。如果省略编码,不同操作系统可能使用不同默认编码,中文内容更容易出现乱码或读取失败。正在加载概念检查...
读取方法
文件读取常用方法有三种:
read():读取整个文件内容,返回字符串。readline():读取一行,返回字符串。readlines():读取所有行,返回字符串列表。
正在加载交互实验...
正在加载概念检查...
正在加载本节练习...
解析单词
下面的程序读取 quotes.txt,去掉标点,把每个单词写入 words.txt。本例假设 quotes.txt 的内容如下:
text
Talk is cheap. Show me the code.
Code never lies, comments sometimes do.
Stay Hungry Stay Foolish.python
import string
with open("words.txt", "w", encoding="UTF-8") as output_file:
with open("quotes.txt", "r", encoding="UTF-8") as input_file:
for line in input_file:
words = line.split()
for word in words:
word = word.strip(string.punctuation)
output_file.write(word + "\n")with 可以嵌套使用。外层负责打开输出文件,内层负责读取输入文件。
运行后,words.txt 会变成:
text
Talk
is
cheap
Show
me
the
code
Code
never
lies
comments
sometimes
do
Stay
Hungry
Stay
Foolish正在加载概念检查...
正在加载本节练习...