使用Python编写一个简单的文件读写程序
发布时间:2023-12-04 08:57:09
下面是一个使用Python编写的简单文件读写程序,包含了读取文件和写入文件的基本操作,并提供了一个使用例子。
# 读取文件
def read_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print("文件不存在")
return None
except Exception as e:
print("文件读取失败:", e)
return None
# 写入文件
def write_file(file_path, content):
try:
with open(file_path, 'w') as file:
file.write(content)
print("文件写入成功")
except Exception as e:
print("文件写入失败:", e)
# 使用例子
file_path = "example.txt"
# 写入文件
content = "Hello, world!"
write_file(file_path, content)
# 读取文件
read_content = read_file(file_path)
if read_content:
print("文件内容:", read_content)
上述程序中,read_file函数负责读取文件内容。它使用with open语句打开文件,并使用read方法读取文件内容。如果文件不存在,会捕获FileNotFoundError异常。其他任何读取文件失败的情况,会捕获Exception异常,并返回None。
write_file函数负责写入文件内容。它也使用with open语句打开文件,并使用write方法写入内容。
使用例子中,首先定义了一个文件路径example.txt,然后调用write_file函数将字符串"Hello, world!"写入文件。
接着调用read_file函数读取文件内容,并将其赋值给read_content变量。如果读取成功,就打印文件内容。
这是一个简单的文件读写程序,可以通过调用read_file和write_file函数来读取和写入文件。你可以根据实际需求对其进行修改和扩展。
