文件读写函数实现
发布时间:2023-06-30 22:20:02
文件读写函数是一种用于读取和写入文件的方法,可以让我们在程序中操作文件。在Python中,我们可以使用内置的open()函数来创建文件对象,然后使用文件对象的方法来读取和写入数据。
下面是一个实现文件读写的函数,具体包括文件读取和文件写入两个函数。
文件读取函数:
def read_file(file_path):
try:
with open(file_path, 'r') as file:
# 读取文件所有内容
content = file.read()
return content
except FileNotFoundError:
print("文件不存在!")
return None
except:
print("文件读取失败!")
return None
文件写入函数:
def write_file(file_path, content):
try:
with open(file_path, 'w') as file:
# 写入文件内容
file.write(content)
print("文件写入成功!")
except:
print("文件写入失败!")
使用上述函数可以实现对文件的读取和写入操作。例如,使用read_file()函数读取文件内容并打印:
content = read_file('example.txt')
if content:
print(content)
else:
print("文件读取失败!")
使用write_file()函数写入数据到文件:
write_file('example.txt', 'Hello, world!')
以上就是文件读写函数的一个简单实现,可以方便地在程序中进行文件操作。当然,根据实际需求,我们还可以对这些函数进行扩展和优化。
