Reputation: 1487
I need to build a simple script in python3 that opens more files inside a directory and see if inside these files is a keyword.
All the files inside the directory are like this: "f*.formatoffile" (* stays for a casual number)
Example:
f9993546.txt
f10916138.txt
f6325802.txt
Obviusly i just need to open the txt files ones.
Thanks in advance!
Final script:
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
Upvotes: 0
Views: 31097
Reputation: 347
This should do the trick:
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.)
Upvotes: 6