Python处理文本的25个经典操作

Python处理文本的优势主要体现在其简洁性、功能强大和灵活性。具体来说,Python提供了丰富的库和工具,使得对文件的读写、处理变得轻而易举。

简洁的文件操作接口

  • Python通过内置的open()函数,可以方便地打开文件进行读取或写入。例如,使用open('example.txt', 'r')可以快速打开一个文件进行读取。
  • 使用上下文管理器(with语句),可在操作完成后自动关闭文件,避免资源泄露。

灵活的文件类型处理

  • Python不仅支持文本文件的处理,还能处理二进制文件、JSON、XML等多种类型的文件,这得益于其丰富的标准库和第三方库。

跨平台兼容性

  • Python的文件处理功能在不同的操作系统上(如Windows、macOS、Linux)都能无缝运行,这为跨平台应用程序的开发提供了极大的便利。

为了更直观了解Python处理文本的优势,本文给出25个Python常用的案例。

  1. 打开文件并读取内容
# 打开文件并读取内容
with open('example.txt', 'r') as file:
    content = file.read()
print(content)
  1. 写入文件
# 写入文件
with open('example.txt', 'w') as file:
    file.write('Hello, World!')
  1. 追加内容到文件
# 追加内容到文件
with open('example.txt', 'a') as file:
    file.write('
New line')
  1. 读取文件的某一行
# 读取文件的某一行
with open('example.txt', 'r') as file:
    line = file.readlines()[0]
print(line)
  1. 逐行读取文件
# 逐行读取文件
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())
  1. 使用fileinput模块修改文件内容
import fileinput

# 使用fileinput模块修改文件内容
for line in fileinput.input('example.txt', inplace=True):
    print(line.replace('old_text', 'new_text'), end='')
  1. 复制文件
# 复制文件
with open('example.txt', 'r') as source, open('copy.txt', 'w') as destination:
    destination.write(source.read())
  1. 移动文件
# 移动文件
import os

os.rename('example.txt', 'moved_example.txt')
  1. 删除文件
# 删除文件
import os

os.remove('example.txt')
  1. 重命名文件
# 重命名文件
import os

os.rename('example.txt', 'renamed_example.txt')
  1. 创建文件夹
# 创建文件夹
import os

os.mkdir('new_folder')
  1. 删除文件夹
# 删除文件夹
import os

os.rmdir('new_folder')
  1. 遍历文件夹中的所有文件
# 遍历文件夹中的所有文件
import os

for file in os.listdir('.'):
    print(file)
  1. 获取文件大小
# 获取文件大小
import os

file_size = os.path.getsize('example.txt')
print(file_size)
  1. 检查文件是否存在
# 检查文件是否存在
import os

if os.path.exists('example.txt'):
    print("文件存在")
else:
    print("文件不存在")
  1. 读取文件并去除空格
# 读取文件并去除空格
with open('example.txt', 'r') as file:
    content = file.read().strip()
print(content)
  1. 读取文件并按行分割
# 读取文件并按行分割
with open('example.txt', 'r') as file:
    lines = file.read().splitlines()
print(lines)
  1. 读取文件并统计行数
# 读取文件并统计行数
with open('example.txt', 'r') as file:
    line_count = sum(1 for line in file)
print(line_count)
  1. 读取文件并查找特定文本
# 读取文件并查找特定文本
with open('example.txt', 'r') as file:
    if 'target_text' in file.read():
        print("找到目标文本")
    else:
        print("未找到目标文本")
  1. 将文件内容转换为列表
# 将文件内容转换为列表
with open('example.txt', 'r') as file:
    content_list = file.read().split()
print(content_list)
  1. 将文件内容转换为字典
# 将文件内容转换为字典
with open('example.txt', 'r') as file:
    content_dict = dict(line.split() for line in file)
print(content_dict)
  1. 写入多行内容到文件
# 写入多行内容到文件
with open('example.txt', 'w') as file:
    file.write('Line 1
Line 2
Line 3')
  1. 使用pathlib模块复制文件
# 使用pathlib模块复制文件
from pathlib import Path

source = Path('example.txt')
destination = Path('copy.txt')
source.replace(destination)
  1. 使用pathlib模块移动文件
# 使用pathlib模块移动文件
from pathlib import Path

file = Path('example.txt')
file.rename('moved_example.txt')
  1. 使用pathlib模块创建和删除文件夹
# 使用pathlib模块创建和删除文件夹
from pathlib import Path

# 创建文件夹
new_folder = Path('new_folder')
new_folder.mkdir()

# 删除文件夹
new_folder.rmdir()

本文这些案例可以帮助大家更高效地处理文本文件,提高大家的Python编程技能。

相关文章

Python 实现从文本文件提取数据并分析保存

一、引言在日常的数据处理工作中,我们经常会遇到从文本文件中提取特定信息并进行分析的需求。本文将详细介绍如何使用 Python 编写代码,从一个包含用户网络使用信息的文本文件中提取用户姓名、入站流量和出...

Python读写docx文件

Python读写docx文件Python读写word文档有现成的库可以处理pip install python-docx安装一下。https://python-docx.readthedocs.io/...

Python读写文本数据

问题你需要读写各种不同编码的文本数据,比如 ASCII,UTF-8或UTF-16编码等。解决方案使用带有 rt 模式的 open()函数读取文本文件。如下所示:# Read the entire fi...

Python如何读取PDF中的文字和图片,请移步至此!

从PDF中提取内容能帮助我们获取文件中的信息,以便进行进一步的分析和处理。此外,在遇到类似项目时,提取出来的文本或图片也能再次利用。要在Python中通过代码提取PDF文件中的文本和图片,可以使用 S...

不要钱,用Python识别图片中的文字

今天我们要学习的是在Python通过调用外部应用识别图片中的文字(OCR)。我们并不需要探究艰深的图像识别的原理和算法,只需要站在巨人的肩膀上知道如何调用百度的文字识别服务就可以用二三十行代码高效实现...