022. 打开一个文件并读取其内容
在 Python 中,可以使用内置的 open()
函数来打开文件并读取其内容。open()
函数返回一个文件对象,通过该对象可以读取文件的内容。以下是一个示例代码,展示如何打开一个文件并读取其内容。
示例代码
假设有一个名为 example.txt
的文件,内容如下:
Hello, World!
This is a test file.
Python is fun!
方式 1:使用 open()
和 read()
方法
# 打开文件并读取内容
file_path = "example.txt"
try:
# 打开文件
with open(file_path, "r") as file:
# 读取文件的全部内容
content = file.read()
# 打印文件内容
print("文件内容:")
print(content)
except FileNotFoundError:
print(f"错误:文件 {file_path} 未找到!")
except Exception as e:
print(f"发生了一个错误:{e}")
方式 2:使用 open()
和 readlines()
方法
# 打开文件并逐行读取内容
file_path = "example.txt"
try:
# 打开文件
with open(file_path, "r") as file:
# 逐行读取文件内容
lines = file.readlines()
# 打印文件内容
print("文件内容:")
for line in lines:
print(line.strip()) # 使用 strip() 去掉每行末尾的换行符
except FileNotFoundError:
print(f"错误:文件 {file_path} 未找到!")
except Exception as e:
print(f"发生了一个错误:{e}")
方式 3:逐行读取文件内容
# 打开文件并逐行读取内容
file_path = "example.txt"
try:
# 打开文件
with open(file_path, "r") as file:
# 逐行读取文件内容
print("文件内容:")
for line in file:
print(line.strip()) # 使用 strip() 去掉每行末尾的换行符
except FileNotFoundError:
print(f"错误:文件 {file_path} 未找到!")
except Exception as e:
print(f"发生了一个错误:{e}")
运行结果
假设文件 example.txt
的内容如下:
Hello, World!
This is a test file.
Python is fun!
运行上述代码后,输出如下:
文件内容:
Hello, World!
This is a test file.
Python is fun!
代码解释
打开文件:
-
使用
open(file_path, "r")
打开文件,其中"r"
表示以只读模式打开文件。 -
file_path
是文件的路径,可以是相对路径或绝对路径。
读取文件内容:
-
file.read()
:读取文件的全部内容,返回一个字符串。 -
file.readlines()
:逐行读取文件内容,返回一个包含每行内容的列表。 -
for line in file
:逐行读取文件内容,每次循环返回文件的一行。
处理异常:
- 使用
try-except
块捕获可能发生的异常,例如FileNotFoundError
(文件未找到)和其他通用异常。
使用 with
语句:
- 使用
with open(...)
语句打开文件可以确保文件在使用后自动关闭,即使在读取文件时发生异常也是如此。
注意事项
文件路径:确保文件路径正确。如果文件和脚本在同一目录下,可以直接使用文件名;否则需要提供相对路径或绝对路径。
文件编码:如果文件内容包含非 ASCII 字符(如中文),可以在 open()
函数中指定文件编码,例如:
with open(file_path, "r", encoding="utf-8") as file:
文件不存在:如果文件不存在,open()
函数会抛出 FileNotFoundError
异常。可以通过 try-except
块捕获并处理这种异常。
视频讲解
BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)