I am trying to find specific strings in a lot of files. For example I am looking for files which contains the string "hello" in a directory and subdirectores.
Lets say my directory system looks like this: File1 and File3 from Dir1 contains the string "hello" while File2 don't. In Dir2 File1 contains the string "hello".
MainDir:
-> Dir1
-> SubDir1
->File1
->File2
-> SubDir2
->File3
-> Dir2
->SubDir1
->File1
->SubDir1.1
->SubDir1.1.1
-> File1
-> File2
My code:
path = "C:\MainDir" #I also get error if I write C:\MainDir\Dir2\SubDir1
word = "hello"
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".txt"):
with open(os.path.join(path, name)) as fle:
my_files_content = fle.read()
if word in my_files_content:
print fle.name
If i write the full path if will find the files which contains the string "hello" (for example: path = "C:\MainDir\SubDir1" or C:\MainDir\Dir2\SubDir1.1\SubDir1.1)
But if I write just the path as in my code it will give me an error "No such file or directory:"
"
on your path name. - zephyr"c:\foo\bar.txt"
, and have\f
and\b
interpreted as escape sequences. You can duplucate backslashes ("c:\\foo\\bar.txt"
) or use raw strings (r"c:\foo\bar.txt"
) to avoid that. - 9000