Python文件操作:读写和错误处理

原创 淡淡的烟草味﹌ 2025-01-23 12:27 53阅读 0赞

在Python中,进行文件操作主要是通过内置的open()函数。这里我们将主要介绍如何读写文件以及错误处理。

  1. 打开文件

    1. # 打开文件并以文本模式读取
    2. file = open('example.txt', 'r')
    3. # 打开文件并以二进制模式写入
    4. file = open('image.jpg', 'wb')
  2. 读取文件内容

    1. content = file.read() # 读取全部内容
    2. print(content) # 输出文件内容
    3. lines = file.readlines() # 按行读取
    4. for line in lines:
    5. print(line.strip()) # 打印每行,去尾空白
  3. 写入文件

    1. file.write('Hello, World!') # 写入一行文本
    2. data = b'binary data' # 转换为二进制数据
    3. file.write(data) # 写入二进制数据
    4. lines = ['line1', 'line2', 'line3']]
    5. file.writelines(lines) # 写入多行文本
  4. 错误处理

    1. try:
    2. # 文件操作代码
    3. except FileNotFoundError:
    4. print("File not found! Please check the file path.")
    5. except PermissionError:
    6. print("Permission denied! Please make sure you have the right permissions.")
    7. except Exception as e:
    8. print(f"An error occurred: {e}")
    9. finally:
    10. # 关闭文件
    11. if 'file' in locals():
    12. file.close()

以上就是Python中进行文件读写以及错误处理的基本操作。

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

发表评论

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

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

相关阅读