0

我是 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()

注意:我尝试删除 "'" +...+"'" 但它也不起作用。有任何想法吗?

4

4 回答 4

2

连接文件和目录时不要忘记文件分隔符。

for files in xlist:

    #if name in files: EDIT: As pointed out by IosiG, Change here too
    if name == files:
        shutil.move(directory + files,newdir) #make changes here

directory + '\\' + files. 
#or 
import os
os.path.join(directory,files)
于 2018-12-03T20:06:19.830 回答
0

谢谢大家的回答,按照建议使用“shutil.move(directory + '\' + files,newdir)”很容易解决这个问题。

import os
import shutil

def shorting_algorithm():
    directory = input("Give the directory you want to search.")
    name = input("Give the name of you files you want to move.")
    newdir = input("Give the new directory.")
    xlist = os.listdir(directory)    

    for files in xlist:
        if name in files:
          shutil.move(directory + '\\' + files,newdir)                 

shorting_algorithm()
于 2018-12-24T11:59:54.253 回答
0

您不需要 for 循环或 if 语句。您已经在主代码块中标识了该文件。由于您明确指定了目录和文件名,因此您无需循环遍历目录列表即可找到一个。当您希望程序自动找到适合某些特定条件的文件时,这更有用。尝试这个:

    import os
    import shutil

    def shorting_algorithm():

            directory = input("Give the directory you want to search.")
            newdir = r'D:\Torrents\Complete\Udemy'
            name = "\\" + input("Give the name of you files you want to move.")
            print(name)
            print(directory)
            shutil.move(directory + name,newdir)

    shorting_algorithm()

去掉多余的引号并将斜杠添加到路径中,将 newdir 转换为原始字符串以避免转义,去掉 for 循环应该可以使这段代码正常工作。我刚刚测试了它,它在这里工作。

于 2018-12-03T20:24:49.833 回答
0

问题是你的循环,你混合了两种迭代方式。会发生以下情况:

for files in xlist: #loop through the names of the files
    if name in files: # look for the name of your file inside the name of another file
        shutil.move(directory + files,newdir)

应该做的是以下几点:

    if name in xlist:
        shutil.move(directory + name,newdir)

或者也

for file in xlist: # only reason for this is if you want input check 
    if str(file) == name:
       # do whatever you need

此外,您必须从输入中删除"'" +...+"'",因为您将这些输入到字符串中,这将使比较变得非常混乱。我还建议使用 raw_input 而不是 input。

于 2018-12-03T20:26:47.837 回答