这是我在这里发表的第一篇文章,因此欢迎对帖子本身的布局等提出批评。
我正在编写一个脚本来自动对文件进行排序。为此,我必须询问文件所在的来源。
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()
我尝试尽可能地简化它。当我输入现有路径时,一切正常。
例如。实际路径\test文件夹存在如果我“不小心”输入了actualpath\testfolde而不带r,否则将再次调用该方法。如果文件夹为空(也用 elif 检查),也会发生同样的情况。
因此:如果在 get_source() 内部再次调用 get_source,则变量 src 将是 NoneType 或包含 None。
我做错了什么?
感谢您的建议!
最佳答案
在get_source
函数中,当你递归调用get_source()
时,你没有指定它返回结果,该语句没有任何作用。在这两个实例中添加 return
关键字,如下所示:
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.")
return get_source()
elif not os.listdir(path_source):
print("The selected path is empty.")
return get_source()
else:
return path_source
关于python - 将不存在的路径分配给字符串时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46518882/