0

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!

1
  • filename = 'file_{}'.format(2000). Commented Jan 21, 2018 at 15:09

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

file_name = f'year_{year}' syntax also works if using Python 3.6+.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.