当涉及到文件操作时,Python
提供了一个名为open()
的内置函数,允许你创建、打开、读取、写入和关闭文件。
一、打开文件
要打开文件,使用open()
函数并提供文件路径和文件模式(只读、写入、追加等)作为参数。open()
函数返回一个文件对象,可以使用它来进行读取或写入操作。
# 打开文件以供读取(默认模式为只读)
file = open("example.txt", "r")
# 打开文件以供写入(覆写)
file = open("output.txt", "w")
# 打开文件以供追加
file = open("append.txt", "a")
二、读取文件内容
2.1 读取整个文件
read()
: 该方法用于读取整个文件的内容。它将文件中的所有内容作为一个字符串返回。
file = open("example.txt", "r")
content = file.read()
print(content)
file.close() # 记得关闭文件
2.2 逐行读取文件:
2.2.1 readline()
该方法用于逐行读取文件内容。每次调用它都会返回文件中的下一行。
with open("example.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)
2.2.2 readlines()
该方法用于读取文件中所有行并返回一个包含所有行的列表。每个列表项都是文件中的一行。
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line)
2.2.3 for line in file
你可以使用 for line in file
的形式,直接在文件对象上进行迭代。这会逐行读取文件内容。
file = open("example.txt", "r")
for line in file:
print(line)
file.close()
以上这些方法可以根据你的需求选择。read()
对于小文件来说很方便,而逐行读取的方法适用于大文件,因为它逐行加载内容,不会一次性加载整个文件。
三、写入内容
要写入文件,可以使用write()
方法。
write
模式会覆盖文件中的内容。当使用 "w"
模式打开一个文件并写入内容时,如果文件已经存在,那么原有的内容将被新内容完全替代。如果文件不存在,将会创建一个新文件。
举例来说,如果有一个名为 example.txt
的文件,其中包含一些文本:
Hello, World!
This is an example.
如果使用以下代码来写入内容到这个文件:
file = open("example.txt", "w")
file.write("New content will overwrite the existing content.")
file.close()
example.txt
文件的内容将会被完全替代,变成:
New content will overwrite the existing content.
四、追加内容
如果希望追加内容而不是覆盖,你可以使用 "a"
模式来打开文件,这将在文件末尾添加新内容而不删除原有内容。
file = open("example.txt", "a")
file.write("This is appended content.")
file.close()
这将在文件末尾添加新内容,不会影响原有的文本。
五、自动关闭文件
为了确保在使用文件后关闭它,可以使用with
语句,这样在退出with
代码块时,文件将自动关闭。
# 打开文件并使用 with 语句
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 文件在 with 块结束后自动关闭
# 在这里文件已经关闭,不能再访问它
六、检查文件是否存在
可以使用os
模块来检查文件是否存在。
import os
if os.path.exists("example.txt"):
print("File exists")
else:
print("File does not exist")
七、异常处理
在文件操作时,要注意异常处理,比如文件不存在或者权限不足的情况。使用try
和except
语句来捕获并处理这些异常。
try:
file = open("nonexistent.txt", "r")
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print("File not found")
ValueError
异常:
is_finished = False
while not is_finished:
try:
n = int(input("Enter a valid integer:"))
print(f"Valid result is: {n}")
is_finished = True
except ValueError:
print("Please enter a valid integer. ")
文件操作对于处理文本文件、日志、配置文件等非常有用。在处理文件时,请记得及时关闭文件,以确保资源得到释放。