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
The file read() method can be used to read the whole text file and return as a single string. The read text can be stored into a variable which will be a string. Alternatively the file content can be read into the string variable by using the with statement which do not requires to close file explicitly.
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
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With