如何在 Python 中读取文件(文本和 JSON)
了解如何在 Python 中读取文件。掌握with open语句、readline、readlines以及安全处理文件异常。
概述
文件处理是任何 Python 开发人员的一项基本技能。从文件中读取数据允许您处理文本文档、配置、日志、数据库和结构化数据集。 Python 通过其内置的“open()”函数使文件操作变得非常简单。
处理文件时,最关键的最佳实践是使用“with”语句,它创建一个上下文管理器。 `with open(...)` 模式保证一旦执行离开块,文件就会被安全、正确地关闭,即使内部发生异常也是如此。忘记关闭文件可能会导致内存泄漏、文件损坏以及锁定其他系统进程的资源。
Python 提供了几种在打开文件后读取数据的方法。 `.read()` 方法将文件的全部内容作为单个字符串返回。 `.readline()` 方法读取一行,非常适合迭代无法放入内存的巨型文件。 `.readlines()` 方法读取所有行并将它们作为字符串列表返回。了解使用哪种方法可以防止内存耗尽并使您的程序更具可扩展性。
代码和执行输出
该脚本演示了如何使用上下文管理器、逐行读取和错误处理来安全地读取文件内容。
read_file.py
在编辑器中尝试# Writing a dummy file first
with open("sample.txt", "w") as f:
f.write("Line 1: Welcome to PyRun!\nLine 2: Python runs in the browser.\nLine 3: Clean and simple.")
# 1. Read entire file contents
with open("sample.txt", "r") as file:
content = file.read()
print("--- Entire File ---")
print(content)
# 2. Read line-by-line (Memory efficient for large files)
print("\n--- Line by Line ---")
with open("sample.txt", "r") as file:
for line in file:
print("Read line:", line.strip())端子输出
--- Entire File ---
Line 1: Welcome to PyRun!
Line 2: Python runs in the browser.
Line 3: Clean and simple.
--- Line by Line ---
Read line: Line 1: Welcome to PyRun!
Read line: Line 2: Python runs in the browser.
Read line: Line 3: Clean and simple.逐步实施
- 使用 with open("filename", "r") as file 语句安全地打开文件进行读取。
- 调用 file.read() 将整个文件内容加载到变量中。
- 使用 for 循环直接迭代文件对象,以有效地逐行读取它。
- 始终指定编码(例如,encoding="utf-8")以实现国际字符兼容性。
常见问题解答
为什么要使用with语句来打开文件?
with 语句创建一个上下文管理器,即使发生错误,退出块时也会自动关闭文件。
如何处理 FileNotFoundError?
将 open() 语句包装在 try- except 块中,捕获 FileNotFoundError: try: with open(...) ... except FileNotFoundError: print("File not find!")。
相关主题
推荐的 Python 资源
通过相关的交互式教程、备忘单和代码比较来扩展您的知识。