欢迎访问宙启技术站
智能推送

如何在 Python 中编写一个读取和写入文件的函数?

发布时间:2023-09-03 11:20:58

在Python中,编写一个读取和写入文件的函数非常简单。以下是一个简单的示例代码,演示了如何编写一个读取和写入文件的函数:

def read_file(file_path):
    try:
        with open(file_path, 'r') as file:
            contents = file.read()
            return contents
    except FileNotFoundError:
        print(f"File {file_path} not found.")
        return None
    except PermissionError:
        print(f"Cannot read file {file_path}. Permission denied.")
        return None
    except Exception as e:
        print(f"An error occurred while reading file {file_path}: {str(e)}")
        return None

def write_file(file_path, contents):
    try:
        with open(file_path, 'w') as file:
            file.write(contents)
        print(f"Successfully wrote to file {file_path}.")
    except PermissionError:
        print(f"Cannot write to file {file_path}. Permission denied.")
    except Exception as e:
        print(f"An error occurred while writing to file {file_path}: {str(e)}")

# 使用示例
file_path = 'example.txt'

# 读取文件
file_contents = read_file(file_path)
if file_contents:
    print(f"Contents of file {file_path}:
{file_contents}")

# 写入文件
new_contents = "This is a new content."
write_file(file_path, new_contents)

以上代码中,read_file函数接收一个文件路径作为参数。它使用open函数以只读模式打开文件,并使用read方法读取文件内容。如果文件不存在,会捕获FileNotFoundError异常,并打印错误信息。如果无法读取文件(例如权限不足),会捕获PermissionError异常。其他异常情况下,会打印一般的错误信息。

write_file函数接收一个文件路径和要写入的内容作为参数。它使用open函数以写入模式打开文件,并使用write方法写入内容。如果无法写入文件(例如权限不足),会捕获PermissionError异常。其他异常情况下,会打印一般的错误信息。

使用示例部分演示了如何调用这两个函数。首先,我们使用read_file函数读取文件内容,并打印在控制台上。然后,我们使用write_file函数将新内容写入文件中。

请注意,以上代码只是一个简单示例,可能需要根据具体需求进行修改。例如,您可能需要添加更多的错误处理逻辑或自定义功能。