Search code examples
pythonfileoperating-systemarchive

How to read multiple txt files from one folder


Is there any method in any python library where I can read multiple txt files from one folder. I have the following code:

path = '/home/paste/archives'

files = filter(isfile, glob.glob('%s/*'%path))
for names in files:
    try:
        with open(names) as f:
            print (names)
    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise

But the code reads all files from the "archives" folder. I would like to read only .txt files. How do I do?


Solution

  • You can limit the glob search with

    files = filter(isfile, glob.glob('%s/*.txt' % path))