【发布时间】:2020-11-05 11:34:20
【问题描述】:
我正在编写代码来查找可能出现在空缺中的特定字符串。我在 .txt 格式的本地文件夹中有一些空缺。我想在所有文件中搜索该字符串,然后将该字符串存储在一个包含所有文件名的新文件中。
我创建了一个包含所有空缺的列表,因为我不希望在我第二次搜索字符串时出现包含搜索字符串的新文件
我有以下代码:
import os
import glob
from datetime import date
import time
today = date.today()
d1 = today.strftime("%d/%m/%Y")
search = "engineer"
vacancies = [filename for filename in glob.glob("*.txt") if not filename.endswith('keyword.txt')]
for filename in vacancies:
with open ("C:\\LOCATION\\txt"+'\\'+filename, 'r', encoding='utf-8') as f:
for line in f:
line = line.lower
for filename in vacancies:
with open ("C:\\LOCATION\\txt"+'\\'+filename) as f:
if search in f.read():
f = open(d1 + " " + search + " keyword.txt","a+", encoding='utf-8')
f.write("Found it in " + filename + '\n')
f.close
我希望我的列表能够过滤掉新文件,但是我收到一条错误消息,指出:FileNotFoundError: [Errno 2] No such file or directory: '05/11/2020 Engineer keyword.txt'
谁能解释为什么这段代码不起作用?
【问题讨论】:
-
旁注:
line = line.lower无效。 -
你能提供示例文本吗?
-
您希望文件
05/11/2020 engineer keyword.txt存在吗? -
@mkrieger1 如果在列表中至少一个文件中找到“工程师”一词,我希望创建该文件。该列表仅包含文件名,而不包含有关 line=line.lower 的实际内容;谢谢,由于主要问题,我还没有测试那行代码。我会在之后进行测试。有什么建议吗?
-
@AlexNe 该列表仅包含文件名,不包含实际内容。你需要什么?