Copy files or directories in Python programming

This script is presented by Patrick Lapre. a member of Unixmen community


#/usr/bin/env python

Small intro: Copying files with a specific pattern from its origin to its final destination ;-)

# import the following modules
# re is needed for patterns
import re
# os.path to define file manipulation
import os.path
# dircache is used for listing directories
import dircache
# shutil is used for copying files
import shutil

# Defined some global variables to be used later on
From_Path = “””/Users/carllapre/test/from/”””
To_Path = “””/Users/carllapre/test/to/”””

a = dircache.listdir( From_Path )
# make a copy of the array to manipulate later on
a = a[:]
# print statement just for debugging
print a

# create string value to be used later on
b = ” “.join( a )
print b

# look it is a pattern ;-)
pattern = re.compile( ‘rbs.*’ )
print pattern

# This is the actual patternmatch
c = re.findall( pattern, b )
print c

# Stick it all together again
e = “”.join( c )

# and now for the split
splitter = re.compile( ‘ ‘ )
d = splitter.split( e )
print d

# Ok this is a loop to check if the file
# already exists in the destination directory
# If not then copy the file to its destination
for i in d:
print i
File_Exist = To_Path + i
# check if the file already exists in its destionation folder
x = ( os.path.isfile( File_Exist ) )
# using a reserved word to check the condition
if x == False:
print “””Copying file to “”” + To_Path
Source = From_Path + i
Destination = To_Path + i
# actual copy action
shutil.copy2( Source, Destination )
print “””File already exists at location “”” + To_Path
print “””n Doing Nothing!!!”””

Please shareShare on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Digg thisShare on StumbleUpon0Share on VKBuffer this page