I would like to write a for loop with these five assigment statements. But I don’t know if and how I can include a loop index variable in the variable name.
fileObj1 = open('c:/users/dell/ch13/textFile1')
fileObj2 = open('c:/users/dell/ch13/textFile2')
fileObj3 = open('c:/users/dell/ch13/textFile3')
fileObj4 = open('c:/users/dell/ch13/textFile4')
fileObj5 = open('c:/users/dell/ch13/textFile5')
How do I have to write the loop?
>Solution :
You can dump all the paths of your variables in a list as such:
fileObj1 = 'c:/users/dell/ch13/textFile1'
fileObj2 = 'c:/users/dell/ch13/textFile2'
fileObj3 = 'c:/users/dell/ch13/textFile3'
fileObj4 = 'c:/users/dell/ch13/textFile4'
fileObj5 = 'c:/users/dell/ch13/textFile5'
flist = [fileObj1, fileObj2, fileObj3, fileObj4, fileObj5]
Now you can call a for loop:
for file in flist:
open(file)