homedir, file copy

Chris Rebert clp2 at rebertia.com
Sun Jan 30 15:59:04 EST 2011


On Sun, Jan 30, 2011 at 12:44 PM, ecu_jon <hayesjdno3 at yahoo.com> wrote:
> hello,
> i am trying to work with windows homedirectory as a starting point for
> some kind of file copy command. i'm testing this on a win7 box so my
> home is c:\Users\jon\
> here is the code snippet i am working on:
>
> import os
>
> homedir = os.path.expanduser('~')
> try:
>    from win32com.shell import shellcon, shell
>    homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
>
> except ImportError:
>    homedir = os.path.expanduser("~")
> print homedir
> print os.listdir(homedir+"\\backup\\")
> homedir.replace("\\\\" , "\\")
> print homedir
> shutil.copy (homedir+"\\backup\\", homedir+"\\backup2\\")
>
>
> output looks like:
> C:\Users\jon
> ['test1.txt', 'test2.txt']
> C:\Users\jon
>
> Traceback (most recent call last):
>  File "D:\spring 11\capstone-project\date.py", line 43, in <module>
>    shutil.copy (homedir+"\\backup\\", homedir+"\\backup2\\")
>  File "C:\Python27\lib\shutil.py", line 116, in copy
>    copyfile(src, dst)
>  File "C:\Python27\lib\shutil.py", line 81, in copyfile
>    with open(src, 'rb') as fsrc:
> IOError: [Errno 2] No such file or directory: 'C:\\Users\\jon\\backup\
> \'
>
>
> why is there still two \\ in the pathfor the copy command?

There aren't. The error message is just showing the repr() of the
string, which involves escaping any literal backslashes in it; note
the quotes around the path in the error message.
Details on repr(): http://docs.python.org/library/functions.html#repr

By way of example:
>>> x = raw_input()
C:\foo\bar
>>> print x
C:\foo\bar
>>> print repr(x)
'C:\\foo\\bar'
>>> print('C:\\foo\\bar')
C:\foo\bar

Note that you can use forward slashes instead of backslashes in
Windows paths in Python, thus avoiding this confusion altogether.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list