python - 将不存在的路径分配给字符串时出现类型错误

标签 python string if-statement typeerror

这是我在这里发表的第一篇文章,因此欢迎对帖子本身的布局等提出批评。

我正在编写一个脚本来自动对文件进行排序。为此,我必须询问文件所在的来源。

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/

相关文章:

python - python中根据常见值将列表的列表转换为字典

带有单引号查找的 Java 正则表达式错误?

php - 在 PHP if 语句中插入 CSS

java - 一个 (log.isDebugEnabled()) 条件每个调试语句出现

python - 如何在 Mac 上使用 PyPy?

python - 如何导入资源模块?

php - 为什么带单引号的字符串在插入数据库时​​会引发错误?

c - 这个用于查找写入的最小数字的基本 if 代码有什么问题

python - 使用 imshow 和 twiny : cannot set xlim

javascript - 在 JavaScript 或 jQuery 中,如何将包含三个单词的单个字符串 ("abc def hij") 转换为 url 编码格式 : "abc+def+hij"?