8

something where the filenames have numbers 1-32 and i want to open them in order in a loop like:

i = 1
while i < 32:
filename = "C:\\Documents and Settings\\file[i].txt"
f = open(filename, 'r')
text = f.read()
f.close()

but this looks for the file "file[i].txt" instead of file1.txt, file2.txt and so on. how do i make the variable become a variable inside double quotes? and yes i know its not indented, please dont think i m that stupid.

I think this might work : Build the filename just like you'd build any other string that contains a variable:

filename = "C:\\Documents and Settings\\file" + str( i ) + ".txt"

or if you need more options for formatting the number:

filename = "C:\\Documents and Settings\\file%d.txt" % i
1
  • Looks like you answered your own question. Commented Aug 17, 2013 at 21:01

3 Answers 3

5

First, change your loop to while i <= 32 or you'll exclude the file with 32 in it's name. Your second option filename = "C:\\Documents and Settings\\file%d.txt" % i should work.

If the numbers in your files are 0 padded, like 'file01.txt', 'file02.txt', you can use %.2d instead of plain old %d

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

3 Comments

If files are 0 padded then we can also do as filename = "C:\\Documents and Settings\\file0%d.txt" % i. I think this should also work.
Don't do that. That would assume that there's a 0 before every number from 1 to 32. %.2d will add 0's if there's only one number. For every number from 10-32, it'll leave the numbers as they are.
If files are have four integers in the end then we can also do as filename = "C:\\Documents and Settings\\file%.4d.txt" % i. I think this should also work. Like filename is file1234.
5

You've already provided an answer. Btw, use with context manager instead of manually calling close():

i = 1
while i < 32:
    filename = "C:\\Documents and Settings\\file%d.txt" % i
    with open(filename, 'r') as f:
        print(f.read())

Comments

2

Yes, the options you gave would work, why not just test it out?

filename = "C:\\Documents and Settings\\file" + str( i ) + ".txt"

or

filename = "C:\\Documents and Settings\\file%d.txt" % i

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.