Tom Smith
Tom Smith

Reputation: 191

Python: How to iterate over files changing their names in loop?

I am a beginner with Python, and I come from MATLAB. What I need to do is create a loop with years from 2000 to 2016. I have a directory with a lot of files, whose filenames contain these years, like "file_2006". How can I create a loop to open the files for specific years? In MATLAB I would do it like:

for i=2000:2016
year=num2str(i);
filename=['file_' year];
X=cdfread(filename); % and then some operations with X that I read here
end

But is it possible to do it in Python? Thank you!

Upvotes: 0

Views: 84

Answers (2)

Derte Trdelnik
Derte Trdelnik

Reputation: 2706

try something like

for year in range(2000,2017):
    file_name = "file_{year}".format(year=year)
    with open(file_name) as file:
        file_data = file.read()

see the documentation about how to work with files here https://docs.python.org/3/tutorial/inputoutput.html

Upvotes: 2

Yes it's possible to do, just use format or %s like this:

for item in range(2000,2016):
    file_name = "%s" % item
    print (print file_name)
    # or do what you want

Upvotes: 0

Related Questions