Python中文件操作:读写错误示例

原创 短命女 2025-02-07 07:48 30阅读 0赞

在Python中,文件操作可能会出现各种错误。以下是一些常见的读写错误示例:

  1. 文件不存在

    1. try:
    2. with open('non_existent_file.txt', 'r') as f:
    3. print(f.read())
    4. except FileNotFoundError:
    5. print("File not found.")
  2. 文件模式不正确

    1. try:
    2. with open('test.txt', 'w') as f: # 应为'x',创建文件不存在时会自动创建
    3. f.write("Hello, World!")
    4. with open('test.txt', 'r') as f:
    5. print(f.read())
    6. except FileNotFoundError:
    7. print("File not found.")
  3. 写入权限不足

    1. try:
    2. with open('/private/etc/config.txt', 'w') as f: # 如果目标文件在私有目录,需要以root权限运行
    3. f.write("This is a私有 file.")
    4. with open('/private/etc/config.txt', 'r') as f:
    5. print(f.read())
    6. except PermissionError:
    7. print("Permission denied for the private file.")

以上就是Python中文件操作可能出现的一些读写错误示例。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,30人围观)

还没有评论,来说两句吧...

相关阅读