我需要在python3中构建一个简单的脚本,在目录中打开更多文件,看看这些文件中是否有关键字。
目录中的所有文件都是这样的:" f * .formatoffile" (*留一个随便的号码)
示例:
f9993546.txt
f10916138.txt
f6325802.txt
很明显我只需要打开txt文件。
提前致谢!
最终剧本:
import os
Path = "path of files"
filelist = os.listdir(Path)
for x in filelist:
if x.endswith(".txt"):
try:
with open(Path + x, "r", encoding="ascii") as y:
for line in y:
if "firefox" in line:
print ("Found in %s !" % (x))
except:
pass
答案 0 :(得分:2)
这应该可以解决问题:
import os
Path = "path of the txt files"
filelist = os.listdir(Path)
for i in filelist:
if i.endswith(".txt"): # You could also add "and i.startswith('f')
with open(Path + i, 'r') as f:
for line in f:
# Here you can check (with regex, if, or whatever if the keyword is in the document.)