2

I would like to iteratively read data from a set of csv files in a for loop. The csv files are named (1.csv, 2.csv and so on)

The normal way to read the data will be

data = pd.read_csv('1.csv')

Please can someone suggest how to replace 1 by i when using a for loop.

I tried data = pd.read_csv(i+'.csv') and data = pd.read_csv(i'.csv') but they did not work.

2 Answers 2

7

Use either percent formatting

 pd.read_csv('%d.csv' % i)

or format

 pd.read_csv('{0}.csv'.format(i))
Sign up to request clarification or add additional context in comments.

2 Comments

Or use string-concatenation: pd.read_csv(str(i)+'.csv') There is nothing bad about it, it's even faster than the format-expression.
This is actually one of the areas of Python where the Perl mantra "there's more than one way to do it" applies. There's also '%i', you can pass a type specifier to format...so many ways!
2

make a separate string?

if i is indeed an integer, using:

filename = str(i) + '.csv'
data=pd.read_csv(filename)

or even:

data=pd.read_csv(str(i)+'.csv')

should be fine :)

3 Comments

I didn't downvote you, but FWIW that won't work for an integer i. You'd have to do str(i) + '.csv'.
There is no information wether i is an int or a str. I don't understand the downvote, too.
Not downvoter, but I think it is clear in question that i is an integer, so probably that was it. I prefer the other answer though.

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.