0

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
3
  • 1
    You probably want to open one file after the other to check for it. Google "loop directory python", which will show you how, then post the code you have if you get stuck Commented Aug 17, 2016 at 8:59
  • 2
    If it always is the same directory, you could try to look into glob.glob. Commented Aug 17, 2016 at 9:16
  • solved. thanks anyway! Commented Aug 17, 2016 at 14:38

1 Answer 1

6

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.)
Sign up to request clarification or add additional context in comments.

2 Comments

I tried it and there's a problem. the script is ok, but i just realized that the txt files are all of a different encoding, in fact it says me: [code]UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe7 in position 5637: invalid continuation byte[/code] is there a way to force all combinations of encoding until the script find the right one?
I SOLVED! I just use "ascii" that seems the most frequent as encoding, and then I added a try-except, and in 2 seconds it found me the file I was looking for! Thanks again. I'll post the final script on the main

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.