根据文件夹的名称将文件夹移动到目录

2024-09-27 17:59:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

注意:我试图删除“'”+…+“'”,但也没有效果。有什么想法吗?你知道吗


Tags: thenameimport文件夹you应用程序inputos
3条回答

在连接文件和目录时不要忘记文件分隔符。你知道吗

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)

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

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

另外,您必须从输入中删除"'" +...+"'",因为您将这些内容输入到字符串中,这将使比较非常混乱。 我还建议使用原始输入而不是输入。你知道吗

您不需要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循环应该可以使这段代码正常工作。我刚测试过,它在这里工作。你知道吗

相关问题 更多 >

    热门问题