程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 文件操作全指南:从读写到高级操作

hfteth 2025-01-06 21:46:52 技术文章 11 ℃

Python 提供了强大的文件操作功能,允许我们对文件进行读写、追加、修改等操作。下面是 Python 文件操作的常用方法和示例:

1. 打开文件 (open())

在 Python 中,使用 open() 函数打开文件。它的基本语法是:

python



file = open('filename', mode)



  • 'filename':文件名(包括路径)。
  • mode:操作模式,常见模式包括:
    • 'r':读取模式(默认)。如果文件不存在,会抛出错误。
    • 'w':写入模式。如果文件不存在,会创建文件。如果文件存在,会清空内容。
    • 'a':追加模式。在文件末尾添加内容。
    • 'rb'/'wb':分别用于二进制文件的读取和写入。

2. 读取文件

  • 逐行读取 (readline())

python



with open('example.txt', 'r') as file:

for line in file:

print(line.strip()) # 使用 strip 去掉每行末尾的换行符



  • 读取所有内容 (read())

python



with open('example.txt', 'r') as file:

content = file.read()

print(content)



  • 读取所有行到列表 (readlines())

python



with open('example.txt', 'r') as file:

lines = file.readlines()

for line in lines:

print(line.strip())



3. 写入文件

  • 覆盖写入 (write())

python



with open('output.txt', 'w') as file:

file.write("This is a new line of text.\n")



  • 追加写入 (write())

python



with open('output.txt', 'a') as file:

file.write("This text will be added to the end.\n")



  • 逐行写入列表内容

python



lines = ['First line\n', 'Second line\n', 'Third line\n']



with open('output.txt', 'w') as file:

file.writelines(lines)



4. 文件关闭

使用 with 语句时,文件会在块结束时自动关闭。你也可以手动关闭文件:

python



file = open('example.txt', 'r')

# 操作文件

file.close()



5. 文件的其他操作

  • 检查文件是否存在

python



import os

if os.path.exists('example.txt'):

print('File exists')

else:

print('File does not exist')



  • 删除文件

python



import os

os.remove('example.txt')



6. 处理二进制文件

当你处理图像、音频等二进制文件时,需要使用 'rb''wb' 模式。

  • 读取二进制文件

python



with open('image.png', 'rb') as file:

binary_data = file.read()



  • 写入二进制文件

python



with open('output_image.png', 'wb') as file:

file.write(binary_data)



7. 异常处理

在进行文件操作时,可能会遇到文件不存在、无法打开等异常,推荐使用 try-except 来处理:

python



try:

with open('nonexistent.txt', 'r') as file:

content = file.read()

except FileNotFoundError:

print("File not found.")



总结

Python 的文件操作非常灵活,支持文本和二进制文件的读写。with 语句可以简化文件操作并确保文件正确关闭。在处理文件时,合理使用异常处理也很重要,以避免程序因错误文件操作而崩溃



Tags:

最近发表
标签列表