Python处理文本的25个经典方法
作者:youqing · 2025-03-28 · 阅读时间:7分钟
Python处理文本的优势主要体现在其简洁性、功能强大和灵活性。具体来说,Python提供了丰富的库和工具,使得对文件的读写、处理变得轻而易举。
一、Python处理文本的优势
1. 简洁的文件操作接口
- Python通过内置的
open()函数,可以方便地打开文件进行读取或写入。例如,使用open('example.txt', 'r')可以快速打开一个文件进行读取。 - 使用上下文管理器(
with语句),可在操作完成后自动关闭文件,避免资源泄露。
2. 灵活的文件类型处理
- Python不仅支持文本文件的处理,还能处理二进制文件、JSON、XML等多种类型的文件,这得益于其丰富的标准库和第三方库。
3. 跨平台兼容性
- Python的文件处理功能在不同的操作系统上(如Windows、macOS、Linux)都能无缝运行,这为跨平台应用程序的开发提供了极大的便利。
二、25个Python常用的案例
1. 打开文件并读取内容
# 打开文件并读取内容
with open('example.txt', 'r') as file:
content = file.read()
print(content)
2. 写入文件
# 写入文件
with open('example.txt', 'w') as file:
file.write('Hello, World!')
3. 追加内容到文件
# 追加内容到文件
with open('example.txt', 'a') as file:
file.write('
New line')
4. 读取文件的某一行
# 读取文件的某一行
with open('example.txt', 'r') as file:
line = file.readlines()[0]
print(line)
5. 逐行读取文件
# 逐行读取文件
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
6. 使用fileinput模块修改文件内容
import fileinput
# 使用fileinput模块修改文件内容
for line in fileinput.input('example.txt', inplace=True):
print(line.replace('old_text', 'new_text'), end='')
7. 复制文件
# 复制文件
with open('example.txt', 'r') as source, open('copy.txt', 'w') as destination:
destination.write(source.read())
8. 移动文件
# 移动文件
import os
os.rename('example.txt', 'moved_example.txt')
9. 删除文件
# 删除文件
import os
os.remove('example.txt')
10. 重命名文件
# 重命名文件
import os
os.rename('example.txt', 'renamed_example.txt')
11. 创建文件夹
# 创建文件夹
import os
os.mkdir('new_folder')
12. 删除文件夹
# 删除文件夹
import os
os.rmdir('new_folder')
13. 遍历文件夹中的所有文件
# 遍历文件夹中的所有文件
import os
for file in os.listdir('.'):
print(file)
14. 获取文件大小
# 获取文件大小
import os
file_size = os.path.getsize('example.txt')
print(file_size)
15. 检查文件是否存在
# 检查文件是否存在
import os
if os.path.exists('example.txt'):
print("文件存在")
else:
print("文件不存在")
16. 读取文件并去除空格
# 读取文件并去除空格
with open('example.txt', 'r') as file:
content = file.read().strip()
print(content)
17. 读取文件并按行分割
# 读取文件并按行分割
with open('example.txt', 'r') as file:
lines = file.read().splitlines()
print(lines)
18. 读取文件并统计行数
# 读取文件并统计行数
with open('example.txt', 'r') as file:
line_count = sum(1 for line in file)
print(line_count)
19. 读取文件并查找特定文本
# 读取文件并查找特定文本
with open('example.txt', 'r') as file:
if 'target_text' in file.read():
print("找到目标文本")
else:
print("未找到目标文本")
20. 将文件内容转换为列表
# 将文件内容转换为列表
with open('example.txt', 'r') as file:
content_list = file.read().split()
print(content_list)
21. 将文件内容转换为字典
# 将文件内容转换为字典
with open('example.txt', 'r') as file:
content_dict = dict(line.split() for line in file)
print(content_dict)
22. 写入多行内容到文件
# 写入多行内容到文件
with open('example.txt', 'w') as file:
file.write('Line 1
Line 2
Line 3')
23. 使用pathlib模块复制文件
# 使用pathlib模块复制文件
from pathlib import Path
source = Path('example.txt')
destination = Path('copy.txt')
source.replace(destination)
24. 使用pathlib模块移动文件
# 使用pathlib模块移动文件
from pathlib import Path
file = Path('example.txt')
file.rename('moved_example.txt')
25. 使用pathlib模块创建和删除文件夹
# 使用pathlib模块创建和删除文件夹
from pathlib import Path
# 创建文件夹
new_folder = Path('new_folder')
new_folder.mkdir()
# 删除文件夹
new_folder.rmdir()
本文这些案例可以帮助大家更高效地处理文本文件,提高大家的Python编程技能。
本文转载自: Python处理文本的25个经典操作
热门推荐
一个账号试用1000+ API
助力AI无缝链接物理世界 · 无需多次注册
3000+提示词助力AI大模型
和专业工程师共享工作效率翻倍的秘密
最新文章
- 为什么要使用Google My Business Reviews API
- 2025年7月第2周GitHub热门API推荐:rustfs/rustfs、pocketbase/pocketbase、smallcloudai/refact
- API设计的首要原则
- 左手用R右手Python系列——百度地图API调用与地址解析/逆解析
- 实测:阿里云百炼上线「全周期 MCP 服务」,AI 工具一站式托管
- 什么是GitHubActions实现开源项目的自动化
- 使用 Whisper API 通过设备麦克风把语音转录为文本
- 如何通过Password Manager(密码管理器)的API调用保护账户安全
- 如何为现代图形API编写渲染器 | Clean Rinse
- Python + BaiduTransAPI :快速检索千篇英文文献(附源码)
- Nexus API 的入门教程与使用指南
- API 规范:设计与最佳实践
热门推荐
一个账号试用1000+ API
助力AI无缝链接物理世界 · 无需多次注册