Problem in Python . . . (It's either parsing or directories.)

Started by
11 comments, last by Splinter of Chaos 17 years, 9 months ago
I hava a code so simple, it just has to work . . . yet some how it doesn't.

import os

saves = os.listdir(dir())
items = 0

for items in saves:
    if (items.endswith('.py')) or (items.endswith('.txt')):
        saves.remove(items)
    else:
        pass
print saves

The goal is just to be able to put this into any program and be able to see every save file in the directory so the user can easilly load his/her file. I do this by excluding every .py and .txt (because I'm only looking for .data files), but for some reason it won't remove the strings I don't want and leaves in EVERY STRING. PS: I know that it would be simpler yet just to write it so that rather than removing the majority files I don't want, I create a new variable and put it the minorities I do want (err, it did work . . .), but I also want to know why this failled.
Advertisement
Don't modify the list while you're iterating over it.

Do this instead:
saves = [ item for item in saves           if not item.endswith(".py") and             not item.endswith(".txt") ]

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
I see, thanks. Although putting a for loop in my variable definition is a concept I will have to beat into my head.

Although now I have a new problem. The code I showcase here works great as a stand-alone piece, but when I changed it for simplicity and turned it into a function after added it to another program, I got a weird result.

 def check_dir(filetype):    import os    dir = os.listdir(dir())    saves = []    items = 0        for i in dir:        if i.endswith(filetype):            saves.append(i)        else:            pass    print 'These are all of the save files:\n', saves


When Python hits the third logical line [dir = os.listdir(dir())] I get the error message back "Local variable 'dir' referenced before assignment." I honestly don't know hwy python doesn't see that as the assignment, so any ideas?

PS: I'll try my save variable with your technique after I fix my 'dir' problem.
You're using the dir() function in the same line that you create a dir variable. At the point after the = sign Python thinks you're trying to reference the dir variable and not the dir() function. Solution: rename the variable.
Quote:Original post by Splinter of Chaos
I see, thanks. Although putting a for loop in my variable definition is a concept I will have to beat into my head.


Well, I'll be happy to wield the hammer: saves = </tt><br><br>List comprehensions are very important in python. If anything, they're faster than the equivalent for loops.<br><br>Or you might just use the <a href=http://docs.python.org/lib/module-glob.html>glob</a> module.<br><br>SiCrane's answer solves your other problem.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Variable renamed.
List formatted.
Problematic still. (I can't believe it.)

import ossDir = os.listdir(dir())saves = [item for item in dir if item.endswith('.data')]print saves


The error I get now for the (s)Dir is this: "coercing from unicode: need string or buffer, list found" I don't get it. And even my new saves variable has a problem too, but it varies between whether whether I run it in the standalone program or the larger one.

Standalone: List not callable
Larger: 'built_in_function_or_method: object is not iterable. (but this may be an artificial result of my bug testing and not naturally occurring in the prog.)

Sorry for being a little troublesome right now, and thanks in advance.

EDIT
I'll play around with Glob, but only for convienience, I will still have to learn, but thanks for the link.
Don't you mean sDir instead of dir in this:

saves = [item for item in dir if item.endswith('.data')]

?
Ah yes. Fixing my typos is obviously not my strong suit, although I still have the two above porblems, list not callable, and unicode. Although I found out that I only get the unicode problem whem I run from the command line and and the list isn't callable when I run it from the IDE (Pywin).
Incidentally, what do you think the dir() function does?
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Quote:Original post by Fruny
Incidentally, what do you think the dir() function does?

Oh wow, didn't even notice that he was doing that. According to 'help(os.listdir)':

Quote:
listdir(...)
listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.

path: path of directory to list

The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.

(emphasis mine)

It requires a path to be passed in, so, if you wanted to list the contents of the current directory, you'd do something like this:
os.listdir(".")


The dir function doesn't really have anything to do with directories--it's actually for listing the attributes of objects (see: help(dir)).

This topic is closed to new replies.

Advertisement