How do i open files in python with variable as part of filename?
python, python-2.7, python-3.x
Solution
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
Problem
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 ```