[Tutor] Zipfile and File manipulation questions.
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Sat Oct 14 07:23:46 CEST 2006
> Is there a way to say :
> for filename in zfile.namelist() contains '.txt, .exe':
Hi Chris,
Yes. It sounds like you want to filter zfile.namelist() and restrict the
entries to those with particular extensions. Try a "list comprehension"
to filter for those interesting filenames:
for filename in [f for f in zfile.namelist()
if os.path.splitext(f)[1] in ('.txt', '.exe')]:
This may be a little dense and hard to read. So you can always break this
out into a function:
#########################################################
def keep_txt_exe_filenames(file_list):
"""keep_txt_exe_filenames: list of strings -> list of strings
Returns a list of all filenames that end in .txt or .exe."""
return [f for f in file_list
if os.path.splitext(f)[1] in ('.txt', '.exe')]
#########################################################
At least that tight expression is documented and can be treated as a black
box. But after you have this function, you can use that helper function:
for filename in keep_txt_exe_filenames(zfile.namelist()):
...
which is usually fairly easy for a person to understand.
> os.remove('*.txt, *.exe')
One way to approach this is with loops. You might find the glob module
useful here:
http://docs.python.org/lib/module-glob.html
It'll help to match the file names for each glob pattern. Again, if you
find yourself doing this a bit, make a helper function to make it easier
to say next time. *grin*
Good luck!
More information about the Tutor
mailing list