当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - Python - Shutil.copy vs fnmatch vs regular expression

问题描述:

I have a directory with multiple files beginning with integers. I am attempting to copy some of them to another directory based on a string pattern within the file name. I can successfully copy multiple files starting with integers (which I commented out), but am having trouble filtering based on the string pattern. I'm using shutil.copy, but am having trouble in determining whether to use regex or fnmatch.

My code below filters correctly, but still copies all files, not files with the specific string 'TEST_Payroll'. Any help to do this would be appreciated. Thanks!!

import re

import os

import fnmatch

import shutil

src_files = os.listdir('C:/Users/acars/Desktop/a')

regex_txt = 'TEST_Payroll'

source = 'C:/Users/acars/Desktop/a'

dest1 = 'C:/Users/acars/Desktop/b'

for file_name in src_files:

#if not file_name.startswith(('0','1','2','3','4','5','6','7','8','9',)):

if fnmatch.filter(file_name, 'TEST_Payroll'):

continue

src = os.path.join(source, file_name)

dst = os.path.join(dest1, file_name)

shutil.copy(src, dst)

网友答案:

How about using,

if re.search(r'TEST_Payroll',file_name):
    #do something with file
else:
    #else do nothing
分享给朋友:
您可能感兴趣的文章:
随机阅读: