首页 > 解决方案 > python - 如何在许多带有python的文本文件中删除以“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)

标签: pythonpython-3.xlabelfile-writingfile-read

解决方案


import glob
import os

path = os.path.dirname(os.path.abspath(__file__))
for name in glob.glob(path+'/*.txt'):
    raw_data = open(name, 'r')
    data_list = raw_data.read().splitlines()
    with open(name, "w") as new_file:
        for row in data_list:
            if row.startswith("1") is False:
                new_file.write(row + '\n')

推荐阅读