python通过通配符复制文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18371768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:35:32  来源:igfitidea点击:

python copy files by wildcards

pythonfilecopyglobshutil

提问by Johnny

I am learning python (python 3) and I can copy 1 file to a new directory by doing this

我正在学习 python (python 3),我可以通过这样做将 1 个文件复制到一个新目录

import shutil 
shutil.copyfile('C:/test/test.txt', 'C:/lol/test.txt')

What I am now trying to do is to copy all *.txt files from C:/ to C:/test

我现在要做的是将所有 *.txt 文件从 C:/ 复制到 C:/test

*.txt is a wildcard to search for all the text files on my hard drive

*.txt 是一个通配符,用于搜索我硬盘上的所有文本文件

回答by Ignacio Vazquez-Abrams

Use glob.glob()to get a list of the matching filenames and then iterate over the list.

使用glob.glob()来获取匹配文件名列表,然后遍历列表。

回答by jseanj

import glob
import shutil
dest_dir = "C:/test"
for file in glob.glob(r'C:/*.txt'):
    print(file)
    shutil.copy(file, dest_dir)

回答by Jamsey

I am using python 2.7 test first to make sure it will work. I used the wildcard * because I add the date to all my text files. filename1_2016_04_18.txt Also some of the text files have different end users attached to the text file. filename2_username.txt

我首先使用 python 2.7 测试来确保它可以工作。我使用通配符 * 因为我将日期添加到我的所有文本文件中。filename1_2016_04_18.txt 还有一些文本文件有不同的最终用户附加到文本文件。文件名2_用户名.txt

import os, glob

directorypath = 'C:\Program Files\Common Files'
os.chdir(directorypath)

files = ['filename1', 'filename2', 'filename3']
print ('A %(files)s'% vars())
for filename in files:
    file1 = filename + "*" + "." + "txt"; print ('1 %(file1)s'% vars())
    file2 = ('%(file1)s') % vars (); print ('2 %(file2)s'% vars())
    file3=glob.glob(file2); print ('3 %(file3)s'% vars())
    for filename4 in file3:
        try:
            if os.path.isfile(filename4):
                    print ('I am deleteing this file %(filename4)s'% vars())
                    os.remove(filename4)
            else:    ## Show an error ##
                    print("Error can not delete text file : %s because file not found" % filename4)
        except OSError, e:  ## if failed, report it back to the user ##
                print ("Error: %s - %s." % (e.filename,e.strerror))