首页 > 解决方案 > 如何在 python 中将多个文件作为输入并存储在变量中

问题描述

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

#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)

标签: pythonpython-3.x

解决方案


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

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

推荐阅读