[Tutor] Re: Tutor digest, Vol 1 #2327 - 10 msgs

Charlie Clark charlie@begeistert.org
Fri Mar 21 15:28:02 2003


On 2003-03-21 at 18:00:10 [+0100], tutor-request@python.org wrote:
> i am trying to create a script that will make dirs for a part of a 
> selected file name using string.split but can only make it work for one 
> file name not many 
> 
> import os
> import string
> 
> os.chdir("dir")
> 
> list = os.listdirs("dir")
> 
> for name in list
>     dir_name string.split(name " - ")[1]
> 
> i can only get dir_name to represent on of the file names in directory 
> but i would like it to be a list of all the names 
> 
> how if possible. 

First of all "list" is a reserved word in Python: use it to turn other 
objects into lists:

$ python
Python 2.1.2 (#1, Jan 26 2002, 03:26:04)
[GCC 2.9-beos-991026] on beos5
Type "copyright", "credits" or "license" for more information.
>>> s = "hi"
>>> list(s)
['h', 'i']
>>>     

You can overwrite this if you want to with Python complaining but it's 
important to be aware of. "dir" is also a built-in function for inspecting 
objects and finding out what you can do with them:
>>> dir("hi")
['capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 
'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 
'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 
'strip', 'swapcase', 'title', 'translate', 'upper']
>>>
          
Michael has already pointed out that strings now have methods (these were 
introduced with Python 1.6 / Python 2.0 at the same time as incremental 
additional "+=") and the string module will become obsolete as some point 
so it's probably better to ignore it now.

Bearing these things in mind.

filenames = os.listdir("my_dir")

dir_list = []
for filename in filenames:
	dir_list.append(filename.split("-")[1])

I'll leave to the gurus to explain the difference between list.append() and 
"+=" but I think you should in general use append().

Furthermore you might want to study os, and os.path more closely as they 
have lots of very useful functions.

Charlie