0

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?

Simone
  • 19
  • 5
  • 2
    Does this answer your question? [Find all files in a directory with extension .txt in Python](https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python) – Brydenr Dec 06 '19 at 22:38

2 Answers2

1

You can limit the glob search with

files = filter(isfile, glob.glob('%s/*.txt' % path))
sjc
  • 1,117
  • 3
  • 19
  • 28
0

With the following snippet, you get all of the files and directories in a given directory and selects only those which have .txt extension:

files = [file for file in os.listdir(path) if file.endswith('.txt')]

Consider my answer if you have a lot of files in one folder (and no subdirectories where you want to get .txt files from) as it is faster.

Arn
  • 1,898
  • 12
  • 26