Random Problems
Larry Bates
larry.bates at websafe.com`
Wed Aug 13 00:43:36 EDT 2008
Lanny wrote:
> Well the othe day I was making a program to make a list of all the songs in
> certian directorys but I got a problem, only one of the directorys was added
> to the list. Heres my code:
>
> import random
> import os
> import glob
>
> songs = glob.glob('C:\Documents and Settings\Admin\My
> Documents\LimeWire\Saved\*.mp3')
> asongs = glob.glob('C:\Documents and Settings\Admin\My
> Documents\Downloads\*\*.mp3')
> songs.append(asongs)
> asongs = glob.glob('C:\Documents and Settings\Admin\My
> Documents\Downloads\*\*\*.mp3')
> songs.append(asongs)
> asongs = glob.glob('C:\Documents and Settings\Admin\My
> Documents\Downloads\*\*\*\*.mp3')
> songs.append(asongs)
> pick = random.choice(songs)
>
> all goes well but pick awalys is from the first directory but songs awalys
> includes all the files I want it to. Im baffaled.
>
>
>
>
> -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net --
>
1) You need to either use raw string for your pathnames or use forward slashes.
This is because backslash is an escape character to Python and if you get any
legal escaped sequence (like \n, \t, etc) it won't work as expected.
songs = glob.glob(r'C:\Documents and Settings\Admin\My
Documents\LimeWire\Saved\*.mp3')
or
songs = glob.glob('C:/Documents and Settings/Admin/My
Documents/LimeWire/Saved/*.mp3')
Yes, forward slashes work just fine on windows.
2) When you have a list (songs) and append another list (asongs) you don't get a
combined list, you get a list with the last element being the second list.
example:
>>> songs = [1,2,3]
>>> asongs = [4,5,6]
>>> songs.append(asongs)
>>> songs
[1, 2, 3, [4, 5, 6]]
>>>
What you wanted was songs.extend(asongs). BTW-Inserting a couple of print
statements would have shown you this problem pretty quickly.
-Larry
More information about the Python-list
mailing list