简体   繁体   中英

How can I take multiple file as input in python & store in a variable

I want to take multiple file as input from command-line like

#python script.py file1.txt file2.txt file3.txt .... file_N.txt

following program can take only one file as input

python script.py file1.txt

But I want to take multiple file as input.

    import sys
with open(sys.argv[1], 'r') as file:
    wordcount = file.read()
    words= wordcount.split()
    #print(words)
    count = {}
    for word in words:
        if word in count:
            count[word]=count[word] + 1
        else:
            count[word] = 1
    print(count)

They are stored in sys.argv. They are stored in array and you can access them through index.

a = str(sys.argv)
// a[0]: file1.txt
// ...

The sys module already contains all the arguments inside the sys.argv which is a list of all arguments passed to the program

The minimum working example I can come up with would be

import sys
names = sys.argv

This code generates a list of all arguments passed to the program. You could of course filter the input to make sure the names are valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM