我的代码:
for filename in os.listdir(directory):
if filename.lower().endswith(".txt"):
line_count = 0
with open(os.path.join(directory, filename),"r", encoding="latin-1") as f:
for line in f:
if "VAR00" in line:
line_count = line_count + 1
with open("Output.txt","a") as o:
o.write(filename + " " + str(line_count) + "\n")
continue
else:
continue
我要处理的.txt文件如下所示:
IRRELEVANT ROW
IRRELEVANT ROW
IRRELEVANT ROW
VAR0001
VAR0002
....
因此,我不想计数的三个无关的行以及以“ VAR00”开头的随机行数。 由于线条很长,因此看起来就像记事本。将一长行拆分为两三个短行,而没有关键字“ VAR00”的计数将导致错误的行数。这就是为什么我需要这种方法的原因,因为所有相关行都应以“ VAR00 *”开头。作为输出,我想要一个具有文件名和行数的.txt文件:
File_1.txt 5
File_2.txt 3
File_3.txt 8
但是代码对我的output.txt中的所有文件返回“ 0”。
打开过程运行良好,因此,如果删除约束“ VAR00”,则所有行都将计数。你能在这里给我一个提示吗?
我已经修复了我的代码中的小错字,但仍然无法产生所需的输出。请重新打开问题并取消保留状态。
答案 0 :(得分:0)
您没有从文件中读取任何行。
将for line in f
更改为for line in f.readlines():
for filename in os.listdir(directory):
if filename.lower().endswith(".txt"):
line_count = 0
with open(filename,"r", encoding="latin-1") as f:
for line in f:
if "VAR00" in line:
line_count = line_count + 1
with open("Output.txt","a") as o:
o.write(filename + " " + str(line_count) + "\n")
continue
else:
continue