请参阅下面的示例脚本。我需要在目录中的多个文本文件上运行它。我知道这是可能的,但我似乎无法正确使用语法。 我相信我需要将以下内容作为一个过程运行?
with open("text.txt", "r") as infile:
for line in infile:
if re.search(r"\b1000\b", line, flags=re.IGNORECASE):
count1 += 1
这是我尝试让它在多个文件上运行失败。
path = 'c:/mypath/'
for filename in os.listdir(path):
open(filename, "r")
for line in filename:
if re.search(r"\b1000\b", line, flags=re.IGNORECASE):
count1 += 1
print(count1)
答案 0 :(得分:0)
您尝试的几个问题。
open
必须分配给文件句柄,你不是那样做filename
是文件名称。您必须加入路径以获取完整文件才能打开例如:
path = r'c:\mypath'
for filename in os.listdir(path):
with open(os.path.join(path,filename), "r") as infile:
for line in infile:
if re.search(r"\b1000\b", line, flags=re.IGNORECASE):
count1 += 1
或更好的内心理解和sum
for filename in os.listdir(path):
with open(os.path.join(path,filename), "r") as infile:
count1 += sum(1 for line in infile if re.search(r"\b1000\b", line, flags=re.IGNORECASE))
或变体(但有些人不喜欢它):
count1 += sum(bool(re.search(r"\b1000\b", line, flags=re.IGNORECASE)) for line in infile)