【问题标题】:Why the dictionary gets populated inside of this while-loop, but it is "empty" outside of the loop?为什么字典在这个while循环中填充,但在循环之外它是“空的”?
【发布时间】: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


【解决方案1】:

我刚刚在flag = Flase之后添加了一个休息:

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
        break
    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}

【讨论】:

    【解决方案2】:

    当用户决定完成该过程时,代码给出了IndexError。我刚刚用

    替换了flags
    while True:
        ...
        if something:
            break
    

    而且效果很好。

    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 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":
            break
        elif uanswer == "Y":
            namefiles.append(input("\nType in the name of the folder:  "))
            while True:
                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":
                    break
        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 = []
    
    print("*"*50)
    print(Subdirectories)
    
    

    【讨论】:

    • 不客气 :) 请注意:通过查看您提供的屏幕截图,我认为您正在通过双击执行代码。因此,当发生错误时它会立即关闭。我建议你从命令行运行你的代码,这样你就可以看到出了什么问题。
    • 感谢您的信息,下次我一定会这样做! ;) 祝你有美好的一天!
    猜你喜欢
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多