python 删除txt的前三行并保存原文件

数据

 

复制代码
#!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 os

def 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)
复制代码

 

posted @   秋刀鱼CCC  Views(10)  Comments(0Edit  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2024-01-13 风云4a
点击右上角即可分享
微信分享提示