我是Python新手,目前正在开发一个应用程序,根据文件夹名将文件夹移动到特定目录。你知道吗
我没有收到错误或警告,但应用程序不会移动文件夹。 代码如下:
import os
import shutil
def shorting_algorithm():
file_list = []
directory = input("Give the directory you want to search.")
newdir = "D:\\Torrents\\Complete\\Udemy"
name = "'" + input("Give the name of the files you want to move.") + "'"
xlist = os.listdir(directory)
print(xlist)
print(name)
for files in xlist:
if name in files:
shutil.move(directory + files,newdir)
shorting_algorithm()
注意:我试图删除“'”+…+“'”,但也没有效果。有什么想法吗?你知道吗
在连接文件和目录时不要忘记文件分隔符。你知道吗
问题是你的循环,你混合了两种迭代方式。 发生的情况如下:
应采取以下措施:
或者也
另外,您必须从输入中删除
"'" +...+"'"
,因为您将这些内容输入到字符串中,这将使比较非常混乱。 我还建议使用原始输入而不是输入。你知道吗您不需要for循环或if语句。您已经在主代码块中标识了该文件。因为您是显式指定目录和文件名,所以不需要在目录列表中进行循环就可以找到一个。当您希望程序自动查找符合某些特定条件的文件时,这一点更为重要。试试这个:
去掉多余的引号并将斜杠添加到路径中,将newdir转换为原始字符串以避免转义,以及去掉for循环应该可以使这段代码正常工作。我刚测试过,它在这里工作。你知道吗
相关问题 更多 >
编程相关推荐