如何在许多带python的文本文件中删除以“ 1”开头的行

问题描述 投票:0回答:1

我在目录中至少有3700个文本文件(实际上是标签),以及相同数量的jpg / jpeg图像。在所有这些文本文件中,数百个文本文件为:

1 0.19140625 0.50078125 0.3078125 0.9484375

我想删除其中存在的每个文本文件中从1开始的行。我尝试了以下内容:

import os
import glob
import errno
path = '~/Documents/txt/*.txt'
path1 = '~/Documents/txt/'
files = glob.glob(path)
txtfile = []
temp_path = os.path.join(path1, 'temp.txt')
for name in files:
    try:
        with open(name, 'r') as f, open(temp_path) as temp:
            for line in f:
                if line.strip() == "1":
                    continue
                temp.write(line)

    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise
#print(txtfile)
python python-3.x label file-writing file-read
1个回答
0
投票

对每个文件使用此:

raw_data = open('data.txt', 'r')
data_list = raw_data.read().splitlines()

with open("data_new.txt", "a") as new_file:
    for row in data_list:
        if int(row[0]) != 1:
            new_file.write(row + '\n')

或:

with open("data_new.txt", "a") as new_file:
    for row in data_list:
        if row.startswith("1") is False:
            new_file.write(row + '\n')
© www.soinside.com 2019 - 2024. All rights reserved.