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)
Don't use global variables. Instead of using string operations to combine pathes, use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.