网站首页 > 基础教程 正文
阅读文件
读取文件的全部内容:
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-03-19 2025年必学的Python自动化办公的15个实用脚本
- 2025-03-19 Python文件操作实战——轻松驾驭数据读写
- 2025-03-19 Python 析构函数使用指南(python中的析构函数)
- 2025-03-19 python散装笔记——181: 音频(python 音频fft)
- 2025-03-19 掌握这几个高级 Python 特性,编写更优代码
- 2025-03-19 破解文件处理难题:用 Python 处理 .txt 文件的必学方法
- 2025-03-19 怎么在Python中读取和写入文件?(用python读取文件内容)
- 2025-03-19 用 Python 从 Word 文档中提取文本(综合指南)
- 2025-03-19 在 Python 中将列表写入文件:完整指南
- 2025-03-19 一学就废|Python基础碎片,文件读写
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)