我需要在 python3 中构建一个简单的脚本,打开目录中的更多文件,并查看这些文件中是否有关键字。
目录内的所有文件都是这样的:“f*.formatofile”(* 为随意数字)
例子:
f9993546.txt
f10916138.txt
f6325802.txt
Run Code Online (Sandbox Code Playgroud)
显然我只需要打开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
Run Code Online (Sandbox Code Playgroud)
这应该可以解决问题:
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.)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30330 次 |
| 最近记录: |