破解文件处理难题:用 Python 处理 .txt 文件的必学方法

liftword6个月前 (12-30)技术文章54

引言:

Python中,对.txt后缀的文件进行多种操作。以下是一些常见的操作及其示例代码:

先让我们来学习一下文件的打开模式及其作用:

读取整个文件:

path =r'D:\file.txt'                      #todo     txt文件所在的路径
with open(path, 'r') as file:
    content = file.read()
    print(content)

逐行读取:

path =r'D:\file.txt'                      #todo     txt文件所在的路径
with open(path, 'r') as file:
    lines = file.readlines()
    print(lines)                             #todo 打印的结果列表展示每一行内容

按行迭代读取:

path =r'D:\file.txt'                      #todo     txt文件所在的路径
with open(path, 'r') as file:
    for line in file:
        print(line, end='')   

with open(path, 'r') as file:
    for _ in range(6):                    # todo 读取指定的行,如前6行
        line = file.readline()
        print(line, end='')

覆盖写入(如果文件不存在则创建,如果文件存在则先清除文件内容并写入新的内容):

path =r'D:\file.txt'                      #todo     txt文件所在的路径
with open(path 'w') as file:
    file.write('Hello, World!\n')

追加写入:

path =r'D:\file.txt'                      #todo     txt文件所在的路径
with open(path, 'a') as file:
     file.write('你好呀\n')

删除指定行:在内存中处理数据

path = r'D:\file.txt'        #todo 替换为你的实际文件路径
line_to_remove = 3      #todo 要删除的行号(1-based)

try:
    with open(path, 'r') as file:
        lines = file.readlines()
    
    #todo  删除指定行(减去 1 因为 list 是 0-based 索引)
    if 1 <= line_to_remove <= len(lines):
        del lines[line_to_remove - 1]
    else:
        print(f"行号 {line_to_remove} 超出文件范围。")

    with open(path, 'w') as file:
        file.writelines(lines)

except FileNotFoundError:
    print(f"文件 {path} 不存在。")
except Exception as e:
    print(f"发生错误: {e}")

检查文件是否存在:

import os
path =r'D:\file.txt'                      #todo     txt文件所在的路径
if os.path.exists(path):
    print('File exists.')
else:
    print('File does not exist.')

删除文件:

import os
path =r'D:\file.txt'                      #todo     txt文件所在的路径
if os.path.exists(path):
    os.remove(path)
    print('File deleted.')
else:
    print('File does not exist.')

重命名文件:

import os
path =r'D:\file.txt'                      #todo     txt文件所在的路径
path_file= r'D:\new_file.txt'   
os.rename(path, path_file)

批量重命名文件:

import os
directory = r'D:\test'
for filename in os.listdir(directory):    #todo 将D:\test目录下所有以.txt结尾的文件,重新命名
    if filename.endswith('.txt'):
        new_name = filename.replace('.txt', '_old.txt')
        os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))

获取文件大小:

import os
path =r'D:\file.txt'  
file_size = os.path.getsize(path)    #todo  获取文件大小
print(f'File size: {file_size} bytes')

读取和写入二进制文件:

path =r'D:\file.txt'  
with open(path, 'rb') as file:   #todo 读取二进制文件
    binary_data = file.read()

with open(path, 'wb') as file:  #todo 写入二进制数据
    file.write(binary_data)

文件锁定(进程间的互斥访问):

import fcntl
path =r'D:\file.txt'  
with open(path, 'r+') as file:
    fcntl.flock(file, fcntl.LOCK_EX)   #todo 锁定文件
    fcntl.flock(file, fcntl.LOCK_UN)  #todo 解锁文件

逐块读取大文件:

chunk_size = 1024  #todo  定义块大小
path =r'D:\large_file.txt'  
with open(path, 'r') as file:
    while chunk := file.read(chunk_size):
        process(chunk)  #todo  对每个块进行处理

处理文件编码:

path =r'D:\file.txt'  
#todo 以特定编码读取文件
with open(path, 'r', encoding='utf-8') as file:
    content = file.read()

#todo 以特定编码写入文件
with open(path, 'w', encoding='utf-8') as file:
    file.write('Some content')

文件内容比较:

import filecmp

result = filecmp.cmp('file1.txt', 'file2.txt')
if result:
    print("Files are identical")
else:
    print("Files are different")

图文说明如下:

相关文章

文件后缀,也称为文件扩展名,用于标识文件的类型

文件后缀,也称为文件扩展名,用于标识文件的类型,帮助操作系统确定使用何种程序来打开文件。这里列举一些常见的文件后缀名及其所代表的文件类型:? 文本文件:? .txt:纯文本文件? .doc、.docx...

在Python中定义Main函数(python main函数语法)

多编程语言都有一个特殊的函数,当操作系统开始运行程序时会自动执行该函数。这个函数通常被命名为main(),并且依据语言标准具有特定的返回类型和参数。另一方面,Python解释器从文件顶部开始执行脚本,...

轻松玩转Python文件操作:移动、删除

哈喽,大家好,我是木头左!Python文件操作基础在处理计算机文件时,经常需要执行如移动和删除等基本操作。Python提供了一些内置的库来帮助完成这些任务,其中最常用的就是os模块和shutil模块。...

Python操作目录(python编程目录)

获取当前工作目录获取执行命令的位置路径拼接路径拆分文件重命名删除文件复制文件遍历文件夹下的文件判断文件是否存在判断目录是否存在获取当前工作目录import sys print(sys.path[0]...