0

I have a directory with spectra in .txt files. And I want to read them all and process one spectrum per time using a for loop, so that I will not have to run the program every single time.

How can I do this?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Vaggelis
  • 17
  • 4
  • 1
    Hello and welcome to StackOverflow. You might find that your question has already been answered elsewhere (see https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory). You might also check out the guidelines before posting a question (https://stackoverflow.com/help/how-to-ask) – Sören Titze Nov 23 '17 at 22:14
  • Possible duplicate of [How can I iterate over files in a given directory?](https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory) – Sören Titze Nov 23 '17 at 22:15
  • Exact duplicate of [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) – AAM111 Nov 24 '17 at 22:41

1 Answers1

0

This will list all of the files in a directory with a given extension:

from os import listdir

def list_files(directory, extension):
    return (f for f in listdir(directory) if f.endswith('.' + extension))

So you can then do:

files = list_files("/my/favourite/directory", "txt")
for f in files:
    # Do something with f