【问题标题】:read and write multiple files separately from the console, python独立于控制台,python 读写多个文件
【发布时间】:2018-06-26 20:57:41
【问题描述】:

我有一个函数,它需要一个强制文件和其他可能的可选文件。目前该函数可以从用户输入读取和写入单个文件。但我想加载和写入与用户从控制台输入输入的文件一样多的文件。为此,我想为一个强制文件名和另一个作为可选参数定义函数。

我如何要求用户在控制台输入中输入一个强制文件和其他所有可能的可选文件名(仅当用户需要时)并在一个函数中分别读取和写入它们而不相互混合。我想分别读取和写入所有输入的文件。

基本上,我想加载用户在控制台输入中输入的所有文件名,并将它们分别写入每个新文件中。

目前我的函数仅从用户输入中加载和读取一个文件。

def read_files(filename, *other):
    with open(filename, 'rU') as f:
        d = json.load(f)

用户输入:

if __name__ == '__main__':
    filename = input('Enter your file name:')

    #Here I am confused how do I ask the possible number of filename and How 
    #do i stop when the user enters all filename
    other = input('Enter your other file name')
    read_files(filename, )

【问题讨论】:

  • 我建议您也查看“argparse”模块。您可以在脚本中添加一个参数,该参数可以采用 1 个或多个名称,然后像“python myscript.py name1.txt name2.txt”一样运行它。
  • 如果您不需要解析选项,使用sys.argv 代替argparse 可能就足够了。

标签: python python-3.x


【解决方案1】:

您可以提示 q 退出会导致停止添加更多文件名:

if __name__ == '__main__':
    filename = input('Enter your file name:')

    other=[]
    while True:
        inp  = input('Enter your other file name (q for quit)')
        if inp == 'q':
            break
        else:
            other.append(inp)
    read_files(filename, other)

编辑:如果没有输入任何内容,停止可能会更方便,所以 while 循环是:

    while True:
        inp  = input('Enter your other file name (press ENTER for quit)')
        if inp == '':
            break
        else:
            other.append(inp)

【讨论】:

  • 谢谢,但是我如何根据在控制台中输入的文件数在函数内分别读取和写入所有可能的可选文件?
  • 这是一个单独的问题。现在您有了一个名为“other”的数组,您将遍历该数组中的每个文件,并打开每个文件。另一个 for 循环,你每次都会调用“read_file(name)”,这就是我的做法。类似:for name in input_files: read_contents(name)(对格式感到抱歉)。这是您可能想要研究的另一个问题:stackoverflow.com/questions/16095855/…
猜你喜欢
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 2020-02-20
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多