dimanche 1 octobre 2017

TypeError when assigning a non-existent path to a string

this is my first post here so i am welcome to criticism regarding the post itself in terms of layout etc.

I am writing a script to automatically sort files. For that I have to ask for a source where the files are.

import os
import os.path
import shutil
import time

def main():
    src = get_source()
    dst = get_destination()
    sort_files_by_modification_time(src, dst)

def get_source():
    path_source = input("Where are the files?\n")
    if not os.path.exists(path_source):
        print("The system cannot find the path specified.")
        get_source()
    elif not os.listdir(path_source):
        print("The selected path is empty.")
        get_source()
    else:
        return path_source

#didnt want to simplify this bit, since in the line path_current = something 
# the error occurs. It is a TypeError: expected str

def sort_files_by_modification_time(path_source)
    for x in range(0, len(os.listdir(path_source))):
        path_current = os.path.join(path_source, os.listdir(path_source)[x])         

if __name__ == '__main__':
    main()

I tried to simplify it as much as possible. When I type in an existing path, everything works fine.

eg. actualpath\testfolder exists

If i were to "accidentally" type actualpath\testfolde without the r the if not will call the method again. The same will happen if the the folder is empty (which is also checked with elif).

So: If inside get_source() get_source gets called again the variable src will be a NoneType or contain None.

What am i doing wrong?

Thanks for advise!

Aucun commentaire:

Enregistrer un commentaire