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…
>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.