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

Is there a way to execute a python code sequentially and with an underterminate amount of variables?

I’ve written a working python code using a predefined variable.

variable = "first_variable"

#code

with open(f"{variable}.txt", "w") as w_file:
    w_file.write("Something")

I now want to adapt the code to accept any number of variables as parameters and process them one after the other.
In the shell, I would like to call it that way:

python3 code.py first_variable second_variable third_variable n_variable

Any idea on how i could do that? I tried using input, creating a function or with a while loop but failed…

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 :

sys.argv is a list of all the arguments passed to python (starting with the name of your script). You can just iterate through each element of it like any other list:

import sys

for variable in sys.argv[1:]:
    with open(f"{variable}.txt", "w") as w_file:
        w_file.write("Something")

Note that sys.argv[0] will be code.py, which you probably don’t want to overwrite.

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