简体   繁体   English

如何将声明的变量存储在数组中

[英]How to store declared variables in a array

I am currently working on a file sorting program and now that I have the selection of the Folders finished I need to assign the right paths to the variables to use them later on to move the files.我目前正在开发一个文件排序程序,现在我已经完成了文件夹的选择,我需要为变量分配正确的路径,以便以后使用它们来移动文件。 My code right now looks like this我的代码现在看起来像这样

import os
import  promptlib

sourcepath = str()
destpath = str()

pathimg = str()
pathtxt = str()
pathaudio = str()
pathvideo = str()
pathexe = str()
pathzips = str()

def get_paths():
    global sourcepath
    global destpath
    sourcepath = promptlib.Files().dir()+"\\"
    destpath = promptlib.Files().dir()+"\\"

def check_or_create_folder():
    get_paths()
    listToCreate = ["images\\","text documents\\","audio files\\","video files\\","executables\\","zips\\"]
    pathToCreate = destpath+"sortedDownloads\\"
    global paths
    try: os.mkdir(pathToCreate)
    except OSError: return
    for elememt in listToCreate:
        try: os.mkdir(pathToCreate+elememt)
        except OSError: break

I thought about storing them in an array and then declaring them element by element maybe something like我考虑过将它们存储在一个数组中,然后逐个元素地声明它们可能类似于

def check_or_create_folder():
    paths = [global pathimg, global pathtxt]  
    listToCreate = ["images\\","text documents\\","audio files\\","video files\\","executables\\","zips\\"]
    pathToCreate = destpath+"sortedDownloads\\"
    for i in range(len(listToCreate)):
        try: os.mkdir(pathToCreate+listToCreate[i])
            paths[i] = pathToCreate+listToCreate[i]
        except OSError: break

but that doesn't work, I tried searching it up but I couldn't find anything so what would be your approach to this problem?但这不起作用,我尝试搜索它,但找不到任何东西,那么您对这个问题的处理方法是什么? thank you before for answering.谢谢你之前的回答。 (i am sorry for my English I'm still 15 years old and it's not that good) (对不起我的英语我还是 15 岁,它不是那么好)

Don't use global variables.不要使用全局变量。 Instead of using string operations to combine pathes, use pathlib.Path .不要使用字符串操作来组合路径,而是使用pathlib.Path

To store your created folders, just use a list:要存储您创建的文件夹,只需使用一个列表:

import promptlib
from pathlib import Path

SUB_FOLDERS = ["images", "text documents", "audio files", "video files", "executables", "zips"]

def get_paths():
    sourcepath = Path(promptlib.Files().dir())
    destpath = Path(promptlib.Files().dir())
    return sourcepath, destpath

def check_or_create_folder():
    sourcepath, destpath = get_paths()
    folders = []
    for folder in SUB_FOLDERS:
        folder = destpath / "sortedDownloads" / folder
        folder.mkdir(parents=True, exist_ok=True)
        folders.append(folder)
    return sourcepath, folders

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM