Opinion on best practice...
torriem at gmail.com
Tue Feb 5 07:04:44 CET 2013
On 02/04/2013 09:14 PM, Anthony Correia wrote:
> 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")
> colDir = os.listdir(objdir)
> for f in colDir:
> activefile = os.path.join(objdir + "\\" + f)
> print ("Removing " + activefile + " from " + objdir)
> In Powershell I would just do:
> $colDir = gci -path "c:\temp2"
> ForEach($file in $colDir)
Yes you could do something like that in Python. I know on linux there
is a module called shutils that provides more shell file handling
abilities to python. Your script as it is listed has a few bugs, though:
- os.listdir() walks the current working directory, not necessarily c:\temp2
- instead of using "\\" in the os.path.join, you can use os.path.sep to
get the current platform's separator character
While I do use python for shell scripting, by itself, it's not very good
at it. I ended up writing my own wrapper function to run external
commands, feed them std-in, and capture standard out and standard error.
I wrapped one of the subprocess module functions. Not sure which. I
can post the file to the list if anyone wants to see it. Also as I
mentioned, on unix machines there is the shutils module.
Still, though, sometimes a proper shell like bash or zsh is going to
work out better for shell scripting than python. Plus if you're going
to be proficient on the Linux command line you need to know their basics
More information about the Python-list