Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create a loop with multiple assignment statements?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading