Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i open files in python with variable as part of filename?

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
like image 305
Arunava Ghosh Avatar asked Aug 17 '13 21:08

Arunava Ghosh


People also ask

How do you read a file and assign to variable python?

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.


2 Answers

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

like image 167
Jason Pierrepont Avatar answered Oct 19 '22 17:10

Jason Pierrepont


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())
like image 22
alecxe Avatar answered Oct 19 '22 17:10

alecxe