【问题标题】:Is there a way in Python to delete directories but keep the files? [duplicate]Python中有没有办法删除目录但保留文件? [复制]
【发布时间】:2021-01-22 06:11:14
【问题描述】:

我有这种复杂的嵌套目录结构,我想摆脱目录,只将所有文件保存在一个目录中。如何在 Python 中做到这一点?

谢谢!

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    以下示例将目录和子目录中的所有文件移动到不同的目录。这是通过使用 'os' 和 'shutil' 操作来列出和移动目录中的文件来完成的。

    import shutil
    import os
    from os import walk
    
    
    #the directory where you're trying to extract files from
    directory_path = "example"
    #the output directory (where you're wanting to store the files)
    output_dir = "output2"
    
    #if the output directory doesn't exist
    if not os.path.exists(output_dir):
        #produce an output directory
        os.makedirs(output_dir)
    
    #if the input directory doesn't exist
    if not os.path.exists(directory_path):
        #throw a warning
        print("The directory you have selected doesn't exist")
        #exit
        exit()
    
    #define a list of directories
    file_list = [] 
    
    #walk allows you to obtain a list of files and directories within a selected path
    #for directories and files in walk(directory_path)
    for (directory, directory_names, filenames) in walk(directory_path):
        #filenames is a list, therefore, we must add the directory to every file in the list
        for files in filenames:
            #add the directory path to the filename
            path = directory + "/" + files
            #append it to the list
            file_list.append(path)
    
    
    #for every filepath in the list
    for filepath in file_list:
        #use shutil to move the file to the output_directory
        shutil.move(filepath, output_dir)
    

    这是一个完成相同目标的简短示例:

    import shutil
    import os
    from os import walk
    
    directory_path = "example"
    output_dir = "output2"
    
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    if not os.path.exists(directory_path):
        print("The directory you have selected doesn't exist")
        exit()
    
    for (directory, directory_names, filenames) in walk(directory_path):
        for files in filenames:
            path = directory + "/" + files
            shutil.move(path, output_dir)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2019-09-06
      相关资源
      最近更新 更多