Sep-26-2022, 12:40 PM
(Sep-26-2022, 11:34 AM)mg24 Wrote: Hi Team,
how to accept multiple values or a list of values from command prompt. and store into single variable.
folderpath, next list of file names to delete.
accept "ab,xy,py,cd,ef,gh" and store into single variable.
**python test.py "C:/Users/malle/OneDrive/Desktop/C/test_data" "ab,xy,py,cd,ef,gh"**
from pathlib import Path import sys def remove_files(folderpath, files): import os os.chdir(folderpath) collection = [] collection = files.split(",") for coll in collection: files = Path.cwd().glob(f"*{coll}*") for file in files: file.unlink(missing_ok=True) if __name__ == "__main__": pattern = "ab,xy,py,cd,ef,gh" root = "C:/Users/malle/OneDrive/Desktop/C/test_data" remove_files(root, pattern)
You could use sys.argv for that!
import sys """ sys.argv returns a list object containing all the arguments passed when running your script, including the script itself. In this case, running the command python test.py "ab,xy,py,cd,ef,gh" will return: ['test.py', 'ab,xy,py,cd,ef,gh'] If, instead of the list of values enclosed in double quotes you pass the individual values separated by spaces, you will get a list with the script name plus every value you passed. python test.py ab xy py cd ef gh will return: ['test.py', 'ab', 'xy', 'py', 'cd', 'ef', 'gh'] Than you can get only the values you want using list comprehension: values = sys.argv[1:] The above gets all the values from sys.argv except the first index, which is the script file. """ arguments = sys.argv values = arguments[1:] print(values)