【发布时间】:2020-05-10 19:10:11
【问题描述】:
我正在尝试通过收集用户关于文件夹名称和他/她想要自动放置在该文件夹中的扩展名的输入来使用 Python 自动化文件管理。
创建字典以将文件夹名称保存为字符串(字典键)并将扩展名保存为字符串列表后,用户填充每个列表,我在填充字典时将它们结合起来。
问题: 我能够使用上述信息填充循环内部的字典,但我已经尝试在 while 循环之外打印字典,但它没有不工作。因此,我的程序无法在字典中没有值的情况下工作。 能否请您检查一下为什么我在退出 while 循环后无法保留字典中的信息?
模拟:程序一直运行到循环的最后部分(见下图),然后关闭窗口,什么也没有发生。
第一部分代码:
import os
# Library that helps to find path of the items
from pathlib import Path
# Create list variables
namefiles = []
nameextension1 = []
flag = True
uanswer = ""
count = 0
count2 = 1
flag2 = True
extbreak = ""
# Create dictionaries to organize the folders
Subdirectories = {}
# This is the while-loop to collect the input from the user and populate the lists/dictionary:*
# Collecting input from the users
while flag:
flag2 = True
uanswer = input("\nWould you like to create a Folder in the Library?\n Please, type 'Y' for 'yes'\n or 'N' for 'no': ")
if uanswer == "N":
flag = False
elif uanswer == "Y":
namefiles.append(input("\nType in the name of the folder: "))
while flag2:
nameextension1.append(input("\nType in the name of the extension.\n EX: .pdf: "))
extbreak = input("\nWould you like to add another extension?\n Please, type 'Y' for 'yes'\n or 'N' for 'no': ")
if extbreak == "N":
flag2 = False
else:
print("\nPlease try again!!!")
# Populating the dictionary
Subdirectories[namefiles[count]] = nameextension1
print (Subdirectories)
count += 1
# Cleaning the lists to use for the next extension
nameextension1 = []
# I don't know if this is relevant, but the following step after the while-loop is this:*
file_formats = {file_format: directory
for directory, file_formats in Subdirectories.items()
for file_format in file_formats}
感谢您的支持,如果我的解释不是很清楚,我很抱歉。 如果您有任何问题,请随时发表评论,我会提供尽可能多的细节:)
PS:母亲节快乐!
【问题讨论】:
-
'it doesn't work' 相当模糊,请告诉我们到底出了什么问题 - 你到底得到了什么输出?
-
对不起,我刚刚上传了一张与问题相关的图片。该程序一直工作到该部分,这是while循环的最后一部分(如果uanswer ==“N”:),然后它关闭并且没有任何反应,当我在代码中创建字典时一切正常并且文件得到组织.希望现在更容易理解我的意思。谢谢!
标签: python python-3.x list dictionary automation