吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 843|回复: 3
收起左侧

[讨论] 删除某文件的某一行

[复制链接]
Appled 发表于 2022-7-8 15:50
本帖最后由 Appled 于 2022-7-8 15:55 编辑

[Python] 纯文本查看 复制代码
# coding:utf8
# 用这个文件来删除某文件的某一行
import os

def reset(path):
    i = 0
    filelist = os.listdir(path)  # 该文件夹下所有的文件(包括文件夹)
    for files in filelist:  # 遍历所有文件

        Olddir = os.path.join(path, files)  # 原来的文件路径
        if os.path.isdir(Olddir):  # 如果是文件夹则跳过
            reset(Olddir)
        else:
            i = i + 1
            filename = os.path.splitext(files)[0]  # 文件名
            filetype = os.path.splitext(files)[1]  # 文件扩展名
            filePath = path + '/' + filename + filetype
            print(filePath)
            alter(filePath, "o ")


def alter(file, old_str):
    """
    将替换的字符串写到一个新的文件中,然后将原文件删除,新文件改为原来文件的名字
    :param file: 文件路径
    :param old_str: 需要替换的字符串
    :param new_str: 替换的字符串
    :return: None
    """
    with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
        i=0
        for line in f1:
            i=i+1
            if i == 4 and old_str in line: # 第四行并且字符o在该行里
                print(line)
                continue
            else:
                f2.write(line)
    os.remove(file)
    os.rename("%s.bak" % file, file)


path = r"./ModelNet40/"
reset(path)

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

sholnfei 发表于 2022-7-8 16:42
直接做成小软件行吗
 楼主| Appled 发表于 2022-7-10 18:36
yep96 发表于 2022-7-10 20:48
删除第N行:
sed -i 'Nd' filename
删除第N~M行:
sed -i 'N,Md' filename
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-11 00:00

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表