0
def isim():
    fh = open('hash.txt')
    for line in fh:
        if re.search('Unique description', line):
            print(line, end='')
def main():
    isim()

if __name__ == "__main__": main()

my question is how can read all text file in a directory instead of hash.txt

karthikr
  • 97,368
  • 26
  • 197
  • 188
Onur Dogu
  • 5
  • 1

2 Answers2

3

Use the glob module.

import re
import glob
def isim():
    textfiles = glob.glob(r"C:\mydir\*.txt")
    for fh in textfiles:
        for line in open(fh):
            if re.search('Unique description', line):
                print(line, end='')
def main():
    isim()

if __name__ == "__main__": main()
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
  • i use glob.glob but gives me error NameError: global name 'glob' is not defined textfiles = glob.glob(r "C:\Users\Pc\Desktop\Ex_Files_Python_3_EssT\Exercise Files\09_Regexes\*.txt") – Onur Dogu Apr 03 '13 at 15:19
  • @OnurDogu: in Python you have to import modules before you use them. Your code can only have worked if you had `import re`; here you'd need `import glob` at the top. – DSM Apr 03 '13 at 15:29
  • if it works for you, please click the checkbox next to the answer ;) if it doesn't work please let me know. thanks. – twasbrillig Apr 03 '13 at 18:09
  • import re import glob class Parse_Txt: def Search(): textfiles = glob.glob(r"C:\Users\Pc\Desktop\Ex_Files_Python_3_EssT\Exercise_Files\09_Regexes\*.txt") for fh in textfiles: for line in open(fh): if re.search('Unique description', line): print(line, end='') def main(): f = open('example.csv','w') f.write(Parse_Txt.Search()) f.close() if __name__ == "__main__": main() ---------------------------------------------------------- f.write(Duck.arama()) TypeError: must be str, not None
    – Onur Dogu Apr 04 '13 at 09:05
  • You need to return a string from your Search function. I pasted code here that should fix the problem: https://gist.github.com/anonymous/22eda0b3fa4c5b971ab1 – twasbrillig Apr 04 '13 at 09:41
1

Use os.listdir() to list the contents of a directory; you can then add a simple filename filter as needed:

path = '/some/directory'
for filename in os.listdir(path):
    if not filename.endswith('.txt'):
        continue
    filename = os.path.join(path, filename)
    with open(filename, 'r') as fh:
        for line in fh:
            if re.search('Unique description', line):
                print(line, end='')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343