【问题标题】:How can I take multiple file as input in python & store in a variable如何在 python 中将多个文件作为输入并存储在变量中
【发布时间】:2020-04-29 09:52:26
【问题描述】:

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

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

【问题讨论】:

标签: python python-3.x


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    我能想出的最小工作示例是

    import sys
    names = sys.argv
    

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

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多