【问题标题】:copy files based on matching symbol根据匹配符号复制文件
【发布时间】:2021-11-09 18:16:36
【问题描述】:

我有一个包含数千个文件的目录。但是我有一个包含同一目录的文件名的列表。我想从列表的末尾复制包含星号 * 的文件。

列表是

2016-05-23-0145-30S.INMME_012*
2016-07-12-0546-26S.INMME_006
2016-07-17-2033-16S.INMME_003
2016-07-19-1307-57S.INMME_003
2016-08-17-1649-12S.INMME_006*
2016-09-03-1151-03S.INMME_003
2016-10-21-1240-02S.INMME_006*
2016-10-21-1310-38S.INMME_006
2016-10-23-0016-39S.INMME_006
2016-10-23-0859-50S.INMME_006

所以我想将2016-05-23-0145-30S.INMME_012* 2016-08-17-1649-12S.INMME_006* 2016-10-21-1240-02S.INMME_006* 复制到单独的目录。

【问题讨论】:

    标签: python linux bash for-loop sed


    【解决方案1】:
    import os
    import shutil
    def copy_file_to_another_location(inputpath, outputpath, filename):
       if not os.path.exists(outputpath):
          os.makedirs(outputpath)
       shutil.copy(str(os.path.join(inputpath, filename)).replace("\n", "").replace("*", ""), str(os.path.join(outputpath, filename)).replace("\n", "").replace("*", ""))
       print("Copying: " + str(os.path.join(inputpath, filename)).replace("\n", ""))
    
    inputpath = r'C:\\Users\\me\\Desktop\\tada\\in'
    outputpath = r'C:\\Users\\me\\Desktop\\tada\\out'
    file = open("asd.txt", "r", encoding="utf-8")
    files_list = file.readlines()
    for file in files_list:
       if "*" in str(file):
          copy_file_to_another_location(inputpath, outputpath, file)
    

    注意:此脚本将确保从输入位置到输出位置保持文件夹结构(例如:inputlocation/some_folder/2016-10-23.... 将被复制到 outputlocation/some_folder/2016-10-23...

    【讨论】:

    • 先生,我有数千个文件很难编辑文件列表...请您以自动方式提出建议
    • 您不必编辑列表,您在说什么?你的列表是什么格式的,是保存在.txt文件还是csv文件?
    • 你去。我已经编辑了脚本。这将读取 .txt 文件并将其中的所有行保存到一个列表中,然后检查列表中的每一行是否包含“*”
    • print("正在复制:" + str(os.path.join(inputpath, filename))) ^ SyntaxError: invalid syntax
    • 对不起,在print 一个上面的那一行,最后应该还有一个)。我刚刚添加了它。还要确保在线for file in file_list 更改为for file in files_list。我忘了在file 字的末尾添加 s。 (也编辑了这个)
    【解决方案2】:

    这个bash 脚本将创建一个目录并将文件复制到其中

    #!/usr/bin/env bash
    
    new_dir="temp"
    mkdir $new_dir
    
    for l in list; do
        dup=$(sed -n '/*$/p' $l)
        cp $dup $new_dir/
    done
    

    【讨论】:

    • 不读取我的列表,即保存在 lst.txt 中
    • 如果您不指定列表名称,它将不会读取您的列表。我一般使用名单。在您的情况下,您需要将列表更改为 lst.txt 例如for l in lst.txt
    • 它什么也没做......也许 cat 需要阅读类似cat list的列表
    • cat 是为了什么?我认为不需要在脚本中添加任何内容。它将在您的密码中创建一个名为temp 的目录。如果列表中的文件存在,它会将其复制到临时目录。 ls temp查看
    • 创建目录并卡住////如果可能请修改
    猜你喜欢
    • 2021-10-28
    • 2021-01-02
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2013-11-03
    • 2016-08-13
    • 1970-01-01
    相关资源
    最近更新 更多