I am trying to place all files within a directory into it's own individual folder. When trying to declare the variable 'folders' I enumerate the list of files and try to append the enumerated list number to the end of the folder name, so the folders would look something like... FOLDER_1, FOLDER_2, FOLDER_3, where the trailing digit is generated from enumeration of the files in the directory.
However my code below lists them all as 'FOLDER_0' and then hits an overwrite error, my increment doesn't seem to be working, any direction into what I am doing wrong would be much appreciated.
PATH = "C:/Temp/"
def main():
files = [ join(PATH, f) for f in listdir(PATH) if isfile(join(PATH, f)) ]
for i, f in enumerate (files):
folders = [ PATH+"FOLDER_"+str(i)+"/" for f in files ]
fileslook like after your list comprehension?foldersafter the for-loop? Now you iterate through files but usefnowhere, i.e. the last line is equivalent to folders = [ PATH+"FOLDER_"+str(i)+"/" ] * len(files), which may not be what you want. Also, you are using the variableftwice (outer and inner loop), which really may cause problems.forcycle, a new variablefoldersis created. You must initialize an empty variablefolders = []before theforcycle and then use thelist.append()method or the+=operator to add a new item:folders.append([ PATH+"FOLDER_"+str(i)+"/" for f in files ])enumerateif you do not need it? You can also use:for i in range(len(files))or make a one-line function as for thefilesvariable:folders = [ PATH+"FOLDER_"+str(i)+"/" for i in range(len(files)) ]