[Tutor] File copying - best way?
fleet@teachout.org
fleet@teachout.org
Sat, 4 Aug 2001 23:35:31 -0400 (EDT)
Thanks again, Michael. Thanks also to that electric personality, Tesla
Coil! :)
>From a beginner's perspective, I'm finding this constant ongoing discovery
of additional modules a little disconcerting. For a 24-line (so far)
shell script, I now have 5 modules to import. (And if I remove the "try"
tests, only 8 lines!) Is there a list somewhere that breaks the modules
down into categories such as "file handling" (and that includes ALL the
modules pertaining to file handling)?
(I even thought of os.popen("cat file1 > file2") !) :)
It's late and I'm getting grumpy. Tomorrow is another day!
Best regards and thanks again!
- fleet -
On Sat, 4 Aug 2001, Michael P. Reilly wrote:
> On Sat, Aug 04, 2001 at 09:22:05PM -0400, fleet@teachout.org wrote:
> > Between
> > os.popen("cp /path1/newfile /path2/oldfile")
> > and
> > open("/path1/newfile","w").write(open("/path2/oldfile","r").read())
> >
> > Which, if either, is the "preferred" method of copying a file? The second
> > will raise an IOError if it fails. I have no clue how to test the first.
> >
> > Are there other and/or better methods of copying a file?
>
> I am more partial to the copy2() function in the "shutil" module.
> It is more like "cp -p" on UNIX. It is also portable.
>
> Otherwise, I would write it out explicitly:
>
> infile = open("/path2/oldfile", "rb")
> outfile = open("/path1/newfile", "wb")
> block = infile.read(8192)
> while block:
> outfile.write(block)
> block = infile.read(8192)
> outfile.close()
> infile.close()
>
> The problem with keeping everything on one line is that a) it is harder
> to debug (possibly stepping through code or adding print statements),
> and b) it is harder to insert try-except clauses later if you need them.
>
> Also, if the file is large, reading everything at once can be a big
> waste of memory (and might even overflow the memory on larger programs).
> Reading in chucks is much more efficient. And unless you know you want
> to get lines, always copy in binary.
>
> -Arcege
>
>