简体   繁体   中英

Transfer files from one directory to another if they match a condition using python

I need to use python to move/copy files from one directory to another in UNIX if the filenames match a certain condition, eg filename1 = extra_filename2. I have prepared the below script but its giving errors. Can somebody correct me please:

#!/usr/bin/python
import shutil, fnmatch, os

for filename in os.listdir('/home/root/Desktop/'):
        try:
                file1 = fnmatch.fnmatch(filename, '*.txt')
                file2 = fnmatch.fnmatch(filename, '*.txt')

        if file1 = extra_'file2'
                print "True"

shutil.copy2('/home/root/Desktop/file1','/home/root/Desktop/Archive',follow_symlinks=True)
import shutil,glob
for fname in glob.glob("/path/to/some*.txt"):
    shutil.copy("/dest/path",fname)

Thank you all for your response, my apologies that i couldnt convey my query and i just provided a raw code, it was absolutely wrong. Basically i was looking for something like below :

#

import os import shutil import re

source = ("sourcePath")

files = os.listdir(source)

for name in files: fullpath = source + "/" + name Name2 = name + "filename2" #print fullpath if re.match("filename regex", name) and Name2 in files:

  #shutil.rmtree("destinationPath"+name) shutil.copytree(fullpath, "destinationpath"+name) shutil.copytree(fullpath, "destinationpath"+Name2) 

print "Finished"

#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM