shutil module

Pierre Rouleau pieroul at attglobal.net
Mon Nov 18 20:37:07 EST 2002


Harvey Thomas wrote:

>>i wanted to copy a file to another directory so i used the shutil module's copy() function. The name of this file will >>change everyday.eg, events-18-Nov-2002.txt and tomorrow will be events-19-Nov-2002.txt
>>
>>i used:
>>import shutil
>>import glob
>>shutil.copy (glob.glob(r'c:\winnt\temp\events*'), r'c:\temp')
>>
>>i couldn't seem to copy the file to c:\temp..it says
>>Traceback (most recent call last):
>> File "<pyshell#132>", line 1, in ?
>>   shutil.copy(glob.glob(r'c:\winnt\temp\events-*'),r'c:\temp')
>> File "C:\Python22\lib\shutil.py", line 61, in copy
>>   dst = os.path.join(dst, os.path.basename(src))
>> File "C:\Python22\Lib\ntpath.py", line 190, in basename
>>   return split(p)[1]
>> File "C:\Python22\Lib\ntpath.py", line 149, in split
>>   while i and p[i-1] not in '/\\':
>>TypeError: 'in <string>' requires character as left operand
>>
>>i checked the output of glob and it says
>>
>>>>>glob.glob(r'c:\winnt\temp\events-*')
>>>>
>>['c:\\winnt\\temp\\events-18-Nov-2002.txt']
>>
>>could it be the double slash that is making the fault....??
>>
>>thanks for anyhelp
> 
> 
> The arguments to shutil.copy are strings - the pathnames of the source and destination files. glob.glob, however, returns a list of strings, as you can see above where you have a list containing one string -
> ['c:\\winnt\\temp\\events-18-Nov-2002.txt'].
> 
> So, try (untested)
> 
> for src in glob.glob(r'c:\winnt\temp\events*'):
>     shutil.copy (src, r'c:\temp')
> 

How about a little function that make sure that you always use forward 
slashes (even under Windows) called unixpath() and then using 
shutil.copy() with normal forward slashes (which work in Windows and are 
more portable) like this:

def unixpath(thePath) :
    """Return a path name that contains Unix separator.

    [Example]
    >>> unixpath("d:\\test")
    'd:/test'
    >>> unixpath("d:/test/file.txt")
    'd:/test/file.txt'
    >>>
    """
    thePath = os.path.normpath(thePath)
    if os.sep == '/':
       return thePath
    else:
       return thePath.replace(os.sep,'/')


allFiles = glob.glob('c:/winnt/temp/events*')
for index in xrange(len(allFiles)):
    shutil.copy(unixpath(allFiles[ii]),'c:/temp')


-- 
   Pierre Rouleau






More information about the Python-list mailing list