数据
#!usr/bin/env python # -*- coding:utf-8 _*- """@author:Suyue @file:raindrop.py @time:2025/01/$ {DAY} @desc: """ def remove_first_three_lines(file_path):# 读取原始文件的所有行with open(file_path, 'r', encoding='utf-8') as file:lines = file.readlines()# 移除前三行if len(lines) > 3:lines = lines[3:]else:# 如果文件行数少于或等于3行,则清空文件内容lines = []# 将修改后的内容写回到文件中with open(file_path, 'w', encoding='utf-8') as file:file.writelines(lines)# 使用示例 file_path = 'D:/50425-20220108101800-20220108114459-0.txt' remove_first_three_lines(file_path)
结果:
如果是文件夹内的所有txt:
import osdef remove_first_three_lines(file_path):"""删除文件的前三行并保存原文件。:param file_path: 文件路径"""with open(file_path, 'r', encoding='utf-8') as file:lines = file.readlines()# 去掉前三行if len(lines) > 3:lines = lines[3:]else:lines = [] # 如果文件行数少于3行,则清空文件内容 with open(file_path, 'w', encoding='utf-8') as file:file.writelines(lines)def process_txt_files_in_directory(directory):"""处理指定目录中的所有 .txt 文件,删除它们的前三行。:param directory: 目录路径"""for root, _, files in os.walk(directory):for file_name in files:if file_name.endswith('.txt'):file_path = os.path.join(root, file_name)remove_first_three_lines(file_path)if __name__ == "__main__":# 替换为你的文件夹路径directory_path = '/path/to/your/directory'process_txt_files_in_directory(directory_path)