【问题标题】:Copy all the files which begin with the same name to a different directory in python将所有以相同名称开头的文件复制到python中的不同目录
【发布时间】:2020-10-20 08:47:31
【问题描述】:

我的目录如下所示,文件很少。

目录 --111_file.txt --222_file.txt --111_file2.txt --222_sa​​mple.txt

我想将所有以 111 开头的文件复制到一个单独的目录,将 222 复制到另一个目录。我对如何遍历目录并查找以相同名称开头的文件感到困惑。

【问题讨论】:

  • 它并不总是 111 或 222,它可以有任意数量的不同文件路径。它必须遍历整个目录并将以相同名称开头的文件复制到一个文件夹中。另外我不知道文件的名称,我只知道它以数字开头。

标签: python directory copy


【解决方案1】:

以下 bash 脚本复制所有具有模式匹配的文件:

cp 111* dir1;
cp 222* dir2;

【讨论】:

    【解决方案2】:

    如果你想在使用 Python 的程序中实现它,你可以使用 shutil 模块,例如:

    # importing shutil module  
    import shutil  
      
    # Source path  
    source = '/Users/path/to/source'
      
    # Destination path  
    destination = '/Users/path/to/destination'
      
    # Move the content of source to destination  
    dest = shutil.move(source, destination)  
    

    要递归搜索目录和子目录中带有条件的文件,可以使用glob耦合到re

    import os
    import re
    from glob import glob
    
    # Source path 
    source = '/Users/path/to/source'
    
    files = glob(source + '/**', recursive=True) # '/**' and recurvise=True allow to search in subdirectories
    files_to_move = [f for f in files if re.match('^\d', os.path.split(f)[1])] # '^\d' searchs for every files which start with a digit
    

    【讨论】:

    • 请查看评论
    【解决方案3】:

    嘿,在 python 中你可以使用shutil lib。

    例如:

    import shutil
    import os
    
    prefix_1 = '111'
    prefix_2 = '222'
    
    curr_working_dir = os.getcwd()
    
    target1 = 'traget_path_1'
    target2 = 'target_path_2'
    
    files = os.listdir() #Path which includes you source files
    
    for file in files:
       if prefix_1 in file:
           shutil.copyfile(curr_working_dir+'/'+file,target_1)
       elif prefix_2 in file:
           shutil.copyfile(curr_working_dir+'/'+file,target_2)
       else:
          pass
    
    

    最好的问候

    【讨论】:

    • 请查看评论。
    猜你喜欢
    • 2020-12-23
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    相关资源
    最近更新 更多