网站首页 > 基础教程 正文
阅读文件
读取文件的全部内容:
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基础碎片,文件读写
- 05-14CSS基础知识(一) CSS入门
- 05-14CSS是什么? CSS和HTML有什么关系?
- 05-14什么是CSS3?
- 05-14CSS如何画一个三角形?
- 05-14初识CSS——CSS三角制作
- 05-14Wordpress建站教程:给图片添加CSS样式
- 05-14HTML和HTML5,css和css3的区别有哪些?
- 05-14Html中Css样式Ⅱ
- 最近发表
- 标签列表
-
- jsp (69)
- pythonlist (60)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- mysql教程 (60)
- pythonif (86)
- location.href (69)
- deletesql (62)
- c++模板 (62)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)