【问题标题】:How do I move files with a certain word in their name, but only those files?如何移动名称中包含特定单词的文件,但只移动那些文件?
【发布时间】:2021-06-20 19:57:40
【问题描述】:

我正在尝试编写一个程序,该程序将使用 Python 根据文件名将我的文件分类到文件夹中。但是,我不确定如何执行此操作。

这是我已经知道怎么做的,它移动一个文件,但只移动一个。

import shutil

original = r'C:\Users\******\Documents\stacktest\cat1.txt'
new = r'C:\Users\******\Documents\stacktest\cat\cat1.txt'

shutil.move(original, new)

这会将 cat1.txt 文件移动到 cat 文件夹中。

抱歉,如果这篇文章不清楚。如果需要,我会尽力澄清。如果有人能帮我解决这个问题,那么感谢您的帮助!

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    我不确定您要移动哪些文件,比如说,您有一些预先的标准。如果您有明确的文件列表,只需让filenames=<list of names> 跳过读取所有文件并过滤它们。

    import os
    import shutil
    
    folder_from = r'C:\Users\******\Documents\stacktest'
    folder_two = r'C:\Users\******\Documents\stacktest\cat'
    
    # read all files in the folder
    # note that os.listdir returns all files and directories in the folder
    filenames = [f for f in os.listdir(folder_from) if os.isfile(os.join(folder_from, f))]
    
    # filter filenames by the criteria you have in mind
    filenames = list(map(<function that filters>, filenames))
    
    # move the files
    for f in filenames:
        shutil.move(os.path.join(folder_from, f), os.path.join(folder_to, f))
    
    

    【讨论】:

      猜你喜欢
      • 2016-11-06
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2015-03-06
      相关资源
      最近更新 更多