使用Python函数进行文件操作:读取、写入和追加
发布时间:2023-07-04 05:46:06
在Python中,可以使用内置的open()函数进行文件操作,包括读取、写入和追加内容到文件中。
读取文件内容:
def read_file(filename):
try:
with open(filename, "r") as file:
content = file.read()
return content
except FileNotFoundError:
print(f"File '{filename}' not found.")
return None
except Exception as e:
print(f"Error reading file '{filename}': {str(e)}")
return None
写入文件内容:
def write_file(filename, content):
try:
with open(filename, "w") as file:
file.write(content)
print(f"Successfully written to file '{filename}'.")
except Exception as e:
print(f"Error writing to file '{filename}': {str(e)}")
追加内容到文件中:
def append_file(filename, content):
try:
with open(filename, "a") as file:
file.write(content)
print(f"Successfully appended to file '{filename}'.")
except Exception as e:
print(f"Error appending to file '{filename}': {str(e)}")
要读取文件内容,你可以调用read_file函数并传递文件名作为参数。这将返回文件的内容。
要写入文件内容,你可以调用write_file函数并传递文件名和要写入的内容作为参数。
要追加内容到文件中,你可以调用append_file函数并传递文件名和要追加的内容作为参数。
注意:在写入或追加文件时,如果文件不存在,Python会自动创建文件。如果文件已存在,则文件内容将被覆盖(写入文件)或在末尾添加(追加到文件)。确保传递正确的文件名和正确的文件路径。
以上是读取、写入和追加文件内容的基本示例。你可以根据自己的需要进行更改和自定义。
