Question

So I'm a newb :) Python question

I have a list of files and I'm looking to open/read these files using an I/O method

I understand if I explicitly go through each test file I've created and opening them one by one would be fine but how about if I have an unknown file and I tell it to be open/read, how would this be done?

Logically thinking, it sounds like I need to create a variable and assign it to a list of files and from there tell it open all the files in the list. So a for loop perhaps?

Was it helpful?

Solution

You can do it as follows:

import os
for fl in os.listdir(os.getcwd()):
    with open(fl) as f:
        #do stuff

Alternatively, if your files are not in the same directory as your script, you can do:

for fl in os.listdir('custom/path/to/files'):
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top