从Python函数返回一个字符串

时间:2014-10-13 05:14:31

标签: python string return

def God():
    set_path()

    find_files(path)

def set_path():
    '''Sets file path to inputted directory'''

    # Should path default to a certain directory if path is invalid?
    # (it does here)
    #path = Path(input("Enter path\n"))
    path = Path(input("Specify a directory:\n")
    print("Path set to", path.cwd())
    return path



def find_files(path):
    '''Stores files in current dir and all subdirs to a list'''

    myFiles = []
    for element in path.iterdir():
        if element.is_dir() == True:
            find_files(element)
        else:
            myFiles.append(element)
    print(myFiles)
    return myFiles

*** God函数结合了两个函数,并且应该返回设置路径的目录和子目录中的所有文件的列表,但是我一直收到此错误消息:

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    God()
  File "C:/Users/Project1.py", line 8, in God
    return path
NameError: name 'path' is not defined

关于如何返回字符串以供以后在God函数和所有后续函数中使用的任何想法?

1 个答案:

答案 0 :(得分:0)

你的问题不是set_path没有返回路径 - 返回它 - 但是它的调用者正在丢弃返回值。

要解决此问题,请更改此行:

    set_path()

到此:

    path = set_path()