Opinion on best practice...

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Feb 5 11:12:58 CET 2013

----- Original Message -----
> 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)
>         os.remove(activefile)
> In Powershell I would just do:
> $colDir = gci -path "c:\temp2"
> ForEach($file in $colDir)
> --
> http://mail.python.org/mailman/listinfo/python-list


Is you powershell code printing the file being removed ? does it remove the file as well ?
Because when you say "I would *just* do" you seem to imply that the same actions can be performed with powershell in very few lines.

Anyway, your python code is correct but contain minor issues:

1/ listdir returns all elements in a directory, including subdirectories, you should filter the list to get only files. os.remove will not remove directories.
2/ activefile = os.path.join(objdir, f) # would be the portable way of joining path elements

objdir = os.path.join('C:', 'temp2')
for f in [f for _f in os.listdir(objdir) if os.path.isfile(_f)]:
    os.remove(os.path.join(objdir, f))

Also note that 'shutil' is a module giving you access to a lot of tools for copying, deleting creating files/dir.



The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.

More information about the Python-list mailing list