网站首页 > 技术文章 正文
阅读文件
读取文件的全部内容:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
2. 写入文件
将文本写入文件,覆盖现有内容:
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
3. 向文件追加
将文本添加到现有文件末尾:
with open('example.txt', 'a') as file:
file.write('\nAppend this line.')
4. 将行读取到列表中
读取文件并将每一行添加到列表中:
with open('example.txt', 'r') as file:
lines = file.readlines()
print(lines)
5. 遍历文件中的每一行
处理文件中的每一行:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
6. 检查文件是否存在
在执行文件操作之前检查文件是否存在:
import os
if os.path.exists('example.txt'):
print('File exists.')
else:
print('File does not exist.')
7. 将列表写入文件
将列表中的每个元素写入文件的新行:
lines = ['First line', 'Second line', 'Third line']
with open('example.txt', 'w') as file:
for line in lines:
file.write(f'{line}\n')
8. 使用 With 块处理多个文件
同时使用with块处理多个文件:
with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
content = source.read()
destination.write(content)
9. 删除文件
安全删除文件(如果存在):
import os
if os.path.exists('example.txt'):
os.remove('example.txt')
print('File deleted.')
else:
print('File does not exist.')
10. 读取和写入二进制文件
从文件以二进制模式读取和写入(适用于图像、视频等):
# Reading a binary file
with open('image.jpg', 'rb') as file:
content = file.read()
# Writing to a binary file
with open('copy.jpg', 'wb') as file:
file.write(content)
猜你喜欢
- 2025-05-02 python执行.sql语法和文件(python oracle sql语句跟参数)
- 2025-05-02 python unittest 基本用法(python中testcase)
- 2025-05-02 免费定时运行Python程序并存储输出文档的服务推荐
- 2025-05-02 20 天学 Python 文件操作:Day 1 从 open() 开始
- 2025-05-02 python 文件操作(python 文件操作模块)
- 2025-05-02 pdb,让python文件在linux中跑起来
- 2025-05-02 IDEA中配置Python环境并运行(idea 运行python)
- 2025-05-02 14《Python 办公自动化教程》os 模块操作文件与文件夹
- 2025-05-02 Python自动化办公自学笔记(八)文件操作
- 2025-05-02 使用 Python 监控文件系统(python监控文件变化)
- 258℃Python短文,Python中的嵌套条件语句(六)
- 258℃python笔记:for循环嵌套。end=""的作用,图形打印
- 257℃PythonNet:实现Python与.Net代码相互调用!
- 252℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 107℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 83℃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)