Opinion on best practice...
Ulrich Eckhardt
ulrich.eckhardt at dominolaser.com
Tue Feb 5 02:56:36 EST 2013
Am 05.02.2013 05:14, schrieb Anthony Correia:
> I need to pick up a language that would cover the Linux platform. I use Powershell for a scripting language on the Windows side of things. Very simple copy files script. Is this the best way to do it?
>
> import os
>
> objdir = ("C:\\temp2")
Drop the parens here.
> colDir = os.listdir(objdir)
> for f in colDir:
> activefile = os.path.join(objdir + "\\" + f)
The point of os.path.join is exactly that you don't have to spell out
the system-specific file separator. In this case, it gets called with a
single string, which it return as-is.
> print ("Removing " + activefile + " from " + objdir)
Instead of using + to concat strings, use the format() functionn:
"removing {} from {}".format(activefile, objdir)
Also, if you are using Python 2, print is a statement, not a function,
so you could drop the parens here, too. I would not recommend that
though! Instead, "from __future__ import print_function" and keep using
print() as a function, just like in Python 3.
In general, I would not have stored the result of os.listdir() in a
separate variable but iterated over it directly. For large dirs, it
could also be better to use os.path.walk(), because that doesn't first
build a list and then iterate over the list but iterates over the single
elements directly. This avoids the memory allocation overhead, although
it is unlikely to make a difference in this case and a Premature
Optimization(tm).
Welcome to Python!
Uli
More information about the Python-list
mailing list