import os
import chardet
# os 模块:用于处理文件和目录操作。chardet 模块:用于检测文本文件的编码
def remove_lines_from_txt_files(folder_path, num_lines):
# 从指定文件夹内的所有 .txt 文件中删除指定数量的行。
# 参数:
# folder_path (str): 文件夹路径,表示要处理的文件夹的位置。
# num_lines (int): 要删除的行数,表示每个文件中要删除的行的数量。
for root, dirs, files in os.walk(folder_path):
# 遍历指定文件夹下的所有文件和子文件夹
# root: 当前正在遍历的文件夹路径
# dirs: 当前文件夹下的子文件夹列表
# files: 当前文件夹下的文件列表
for file in files:
if file.endswith(".txt"):
# 针对每个文件,判断是否是 .txt 文件
file_path = os.path.join(root, file)
# 构建文件的完整路径
with open(file_path, "rb") as f:
# 使用二进制模式打开文件,并读取文件的原始数据
raw_data = f.read()
# 读取文件的原始数据
encoding = chardet.detect(raw_data)["encoding"]
# 检测文件的编码
content = raw_data.decode(encoding)
# 将原始数据解码为字符串
lines = content.splitlines(keepends=True)
# 将字符串内容按行拆分
with open(file_path, "w", encoding=encoding) as f:
# 打开文件以写入新的内容
f.writelines(lines[num_lines:])
# 将剩余的行写入文件
# 参数输入
folder_path = r"D:***" # 输入文件夹路径
num_lines = 2 # 要删除的行数(前2行)
remove_lines_from_txt_files(folder_path, num_lines)
print("很顺利,内容删除完成")
Python代码:删除txt文件前n行
最新推荐文章于 2024-05-16 21:41:01 发布