I'm coding an interface with Tkinter and I want to automate a task. The actual function opens a window that allows the user to select files (I specify the type of files. Then the paths of these files are retrieved from other functions to modify the files. Here is my actual function:
def get_path(): #return the path of the selected file(s)
root = Tk()
i= datetime.datetime.now()
day = i.day
month=i.month
root.filename = filedialog.askopenfilenames(initialdir = "Z:\SGI\SYNCBBG",title = "Select your files",filetypes = (("Fichier 1","f6365full_account_refresh*"+str(month)+str(day)+".1"),("Fichier 1","f6365icsh*"+str(month)+str(day)+".1"),("all files",".*")))
root.withdraw()
return (root.filename)
What I want is just to have a function that automatically retrieves all files of a type (that I specify) in two different directories. I did this, and the code runs and prints the result, but after that Python stops responding and there is a bug, so I have to close Python. Another thing is that I'm getting the name of the file, not the absolute path, but it's not the main problem:
def path_L2():
os.chdir("Z:/SGI/SYNCBBG/L2/results/results")
for file in glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1"):
return file
for file in glob.glob("f6365icsh*"+str(month)+str(day)+".1"):
return file
def path_L3():
os.chdir("Z:/SGI/SYNCBBG/L3/results/results")
for file in glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1"):
return file
for file in glob.glob("f6365icsh*"+str(month)+str(day)+".1"):
return file
paths=path_L2()
print(paths)
return
will return immediately return from the function. In your case, you're returning the first result of your first glob
statement in each function, and then exiting the function.
All you want to do is take the lists returned from glob
and add them together. You want something like:
def path_L2():
os.chdir("Z:/SGI/SYNCBBG/L2/results/results")
return glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1") + glob.glob("f6365icsh*"+str(month)+str(day)+".1")
def path_L3():
os.chdir("Z:/SGI/SYNCBBG/L3/results/results")
return glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1") + glob("f6365icsh*"+str(month)+str(day)+".1")
I wouldn't use os.chdir, though - that actively changes your working directory. Also, since your two functions are equivalent except for one string, you should make one function that does all that work. (The point of using functions is to not have to repeat the same code over and over.) I would do the following. (I added some extra variables for the sake of neatness.)
def path_L(l_dir):
path1 = "f6365full_account_refresh*"+str(month)+str(day)+".1"
path2 = "f6365icsh*"+str(month)+str(day)+".1"
glob_expr1 = os.path.join(l_dir, path1)
glob_expr2 = os.path.join(l_dir, path2)
return glob.glob(glob_expr1) + glob.glob(glob_expr2)
Then you can call path_L
to get L2 with:
l2_paths = path_L("Z:/SGI/SYNCBBG/L2/results/results")
l3_paths = path_L("Z:/SGI/SYNCBBG/L3/results/results")