读取文件
学习如何在 Python 中打开并读取文件。
读取文件 是 CoddyKit 上的免费 Python For Kids 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python For Kids 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python For Kids 课程共包含 4 节课。
在 Python 中读取文件
欢迎学习文件处理课程!今天,我们将学习如何在 Python 中打开和读取文件。读取文件可以让程序处理并使用存储在外部文件中的数据。

为什么要读取文件?
读取文件对于许多应用都非常重要,例如:
- 数据分析:处理存储在文件中的大型数据集。
- 日志记录:保存事件或操作的记录。
- 配置:从配置文件中加载设置。
- 用户输入:从文件中读取用户数据。
让我们看看如何在 Python 中读取文件!
打开文件
要在 Python 中读取文件,首先需要使用 open() 函数打开它。该函数会返回一个文件对象,提供从文件中读取内容的方法。
语法:
file_object = open("filename", "mode")
读取整个文件
打开文件后,您可以使用 read() 方法读取其内容。该方法会读取整个文件,并将其作为一个字符串返回。
示例:
# Opens the file in read mode
file = open("example.txt", "r") # 'r' stands for read mode
# Reads the entire content of the file
content = file.read()
# Prints the content
print(content)
# Closes the file
file.close()
逐行读取文件
您不必一次读取整个文件,也可以使用循环逐行读取。这对于处理大型文件很有用。
示例:
# Opens the file in read mode
file = open("example.txt", "r") # 'r' stands for read mode
# Iterates through each line in the file
for line in file:
print(line.strip()) # Prints each line without extra newline characters
# Closes the file
file.close()
使用 with 语句
处理文件时,建议使用 with 语句。这样可以确保其语句块执行完毕后文件会被正确关闭,即使发生错误也是如此。
示例:
# Uses the with statement to open and read the file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need to explicitly close the file
读取特定行
您可以使用 readline() 或 readlines() 等方法从文件中读取特定行。
- readline():读取文件中的下一行。
- readlines():读取所有行,并将它们作为列表返回。
示例:
# Opens the file using with statement
with open("example.txt", "r") as file:
# Reads the first line
first_line = file.readline()
print("First Line:", first_line.strip()) # Output: First Line: [First line content]
# Reads all remaining lines
all_lines = file.readlines()
print("All Lines:", all_lines) # Output: All Lines: ['Second line\n', 'Third line\n', ...]
处理文件路径
打开文件时,需要指定正确的文件路径。文件路径可以是绝对路径,也可以是相对路径。
- 绝对路径:从根目录开始指定完整路径。
- 相对路径:指定相对于当前工作目录的路径。
示例:
# Absolute path example (Windows)
with open("C:/Users/Username/Documents/example.txt", "r") as file:
content = file.read()
print(content)
# Relative path example
with open("files/example.txt", "r") as file:
content = file.read()
print(content)
做得很好!
您已经学会了如何在 Python 中打开和读取文件,包括一次读取全部内容或逐行处理内容。理解文件读取对于在程序中处理数据、记录日志等操作至关重要。请继续练习,处理不同类型的文件,并探索各种文件处理技巧!

常见问题解答
「读取文件」课时是免费的吗?
是的 — 「读取文件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python For Kids 课程的其余内容,请升级到 CoddyKit PRO。 Python For Kids 课程共包含 4 节课。
「读取文件」这节课中我会学到什么?
学习如何在 Python 中打开并读取文件。 你通过在浏览器中直接运行的动手代码来练习 Python For Kids,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python For Kids 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python For Kids 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「读取文件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python For Kids 课中编写并运行代码吗?
能。每节 Python For Kids 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。