网站首页 > 技术文章 正文
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 语句可以简化文件操作并确保文件正确关闭。在处理文件时,合理使用异常处理也很重要,以避免程序因错误文件操作而崩溃
- 上一篇: python读取文件
- 下一篇: Python读写docx文件
猜你喜欢
- 2025-01-06 3分钟教会你用Python读取MySQL中的数据
- 2025-01-06 Python高效管理JSON文件:读写、更新、删除全攻略
- 2025-01-06 读取txt、doc、docx、pdf文件——python
- 2025-01-06 20 天学 Python 文件操作:Day 2 深入理解文件读取方法
- 2025-01-06 python 利用python读取DOC文件
- 2025-01-06 一日一技:在Python中逐行读取文件
- 2025-01-06 python中读取图片的6种方式
- 2025-01-06 Python读写docx文件
- 2025-01-06 python读取文件
- 2025-01-06 Python如何读写xml
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)