首页 > 解决方案 > 独立于控制台,python 读写多个文件

问题描述

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

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

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

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

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

标签: pythonpython-3.x

解决方案


您可以暗示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)

推荐阅读