在python&;中如何将多个文件作为输入;存储在变量中

在python&;中如何将多个文件作为输入;存储在变量中,python,python-3.x,Python,Python 3.x,我想从命令行获取多个文件作为输入,比如 #python script.py file1.txt file2.txt file3.txt .... file_N.txt 以下程序只能接受一个文件作为输入 python script.py file1.txt 但我想把多个文件作为输入 import sys with open(sys.argv[1], 'r') as file: wordcount = file.read() words= wordcount.split()

我想从命令行获取多个文件作为输入,比如

#python script.py file1.txt file2.txt file3.txt .... file_N.txt
以下程序只能接受一个文件作为输入

python script.py file1.txt 但我想把多个文件作为输入

    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)

它们存储在sys.argv中。 它们存储在数组中,您可以通过索引访问它们

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

sys模块已经包含
sys.argv
中的所有参数,sys.argv是传递给程序的所有参数的列表

我能想到的最起码的工作示例是

import sys
names = sys.argv

此代码生成传递给程序的所有参数的列表。当然,您可以过滤输入以确保名称有效。

您可以显示您已经尝试过的内容吗?这是否回答了您的问题?对