如何使用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)
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')

我提出了以下内容:

path = '/home/mzaid/Documents/txt/*.txt'
for name in glob.glob(path):
try:
with open(name, 'r+') as fl:
for line in fl:
if line.startswith("1"):
#not sure what to do here
except IOError as exc:
if exc.errno != errno.EISDIR:
raise

最新更新