使用Python编写一个简单的文件操作程序,可以读取和写入文件
发布时间:2023-12-04 14:47:23
下面是一个简单的文件操作程序,它可以读取和写入文件。使用Python的内置函数来实现这些功能。
def read_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
return "文件不存在"
except:
return "读取文件时发生错误"
def write_file(file_path, content):
try:
with open(file_path, 'w') as file:
file.write(content)
return "文件写入成功"
except:
return "写入文件时发生错误"
# 使用例子
file_path = "example.txt"
file_content = "Hello, World!"
# 写入文件
result = write_file(file_path, file_content)
print(result)
# 读取文件
content = read_file(file_path)
print(content)
在上面的例子中,我们首先定义了两个函数:read_file()和write_file(),分别用于读取和写入文件。这两个函数都接受文件路径作为参数,并使用with open()来打开和关闭文件。
在read_file()函数中,我们尝试读取文件内容,并返回读取到的内容。如果文件不存在,则返回"文件不存在";如果发生其他错误,则返回"读取文件时发生错误"。
在write_file()函数中,我们尝试将给定的内容写入文件。如果写入成功,则返回"文件写入成功";如果发生错误,则返回"写入文件时发生错误"。
在使用例子中,我们指定了一个文件路径example.txt和文件内容"Hello, World!"。我们首先调用write_file()函数将内容写入文件,并打印结果。然后调用read_file()函数读取文件内容,并打印结果。
请注意,这只是一个简单的示例程序,仅用于说明文件操作的基本原理。在实际的应用程序中,您可能需要添加更多的错误处理和异常处理机制。
