python - 独立于控制台,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, )
解决方案
您可以暗示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)
推荐阅读
- javascript - 滚动时如何悬停?
- php - 如何创建自定义页面 Prestashop 1.7
- vue.js - 我对 bootstrap-vue 工具提示位置有一个奇怪的问题
- json - Django - 用模型和数据序列化复杂的上下文结构
- python - 有没有办法在 kivy 中使用 twolistitem 和 recycleview 显示所有 .txt 文件
- javascript - AngularJS 过滤数据,日期为 Today , Week 和 Month
- python - 从 Dataframe 的 4 列创建 3D 矩阵
- bash - 如何在不使用文件的情况下拆分/复制 FIFO
- javascript - 如何在 Nodejs 中正确使用相等运算符
- javascript - GET 或 POST 请求 => 很长的 URL