coping directories

Jussi Salmela tiedon_jano at hotmail.com
Fri Feb 2 11:06:59 EST 2007


Gigs_ kirjoitti:
> hi people
> 
> I have problem with this example, not actually the problem, but
> [code]
> class FileVisitor(object):
>     def __init__(self, data=None):
>         self.context = data
>     def run(self, startdir=os.curdir):
>         os.path.walk(startdir, self.visitor, None)
>     def visitor(self, data, dirname, filesindir):
>         self.visitdir(dirname)
>         for fname in filesindir:
>             fpath = os.path.join(dirname, fname)
>             if not os.path.isdir(fpath):
>                 self.visitfile(fpath)
>     def visitdir(self, dirpath):            # override or extend this 
> method
>         print dirpath, '...'
>     def visitfile(self, filepath):          # override or extend this 
> method
>         print self.fcount, '=>', filepath
> #
> class CVisitor(FileVisitor):
>     def __init__(self, fromdir, todir):
>         self.fromdirLen = len(fromdir) + 1        # here is my problem
>         self.todir = todir
>         FileVisitor.__init__(self, fromdir)
>     def visitdir(self, dirpath):
>         topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
>         os.mkdir(topath)
>     def visitfile(self, filepath):
>         topath = os.path.join(self.todir, filepath[self.fromdirLen:])
>         cpfile(filepath, topath)    #copy contents from filepath to 
> topath[/code]
> 
> 
> When I copy contents from C:\IronPython to C:\temp
> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this 
> self.fromdirLen = len(fromdir) + 1
> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen 
> = len(fromdir) i get contents copied to C:\ (actually to parent dir)
> 
> Can anyone explain me that?
> 
> Thanks!!!
>  :o

Why do you want to change a working program anyway? :)

The result of your change is that os.path.join does the join 
differently. Before the change the join is, for example:
	os.path.join(r'c:\temp', r'AUTOEXEC.BAT')
with a result:
	c:\temp\AUTOEXEC.BAT

After your change the join is:
	os.path.join(r'c:\temp', r'\AUTOEXEC.BAT')
with a result:
	\AUTOEXEC.BAT

This is described in the doc:

  join( path1[, path2[, ...]])

Join one or more path components intelligently. If any component is an 
absolute path, all previous components (on Windows, including the 
previous drive letter, if there was one) are thrown away, and joining 
continues.

HTH,
Jussi



More information about the Python-list mailing list