Populating Lists in Def using Python
Dipping around in python again and need to create a def that will populate a list(content) with the files that os.walk finds from within this directory and then I will re.search through each files looking for content. In learning Python, can someone point me in the right direction. This is what I have so far.
Code:
def list_files ( content=None ): |
Why is the function taking an argument? If you want to have the list remembered the second time function is called, use global variable. Put the return outside of for and it will work. Most importantly, does your function does anything other then just pass through whatever os.walk returns?
Code:
_LIST_FILES = [None] |
what you have is basically ok. Don't use globals unless you have to, (doing so will make your code unmaintable later). I believe you want extend not append and you have the return in the wrong place
Code:
for files in os.walk('var/www/html/data/customer/log', topdown=True): |
Ah, right, I forgot that os.walk has a weird return type. What you want is:
Code:
for dir, _, files in os.walk('var/www/html/data/customer/log'): |
ok I got my function to work using:
Code:
def list_files(): Code:
list_files() Code:
content[3] Code:
['file1', 'file2', 'file3', 'file4']] Code:
In [66]: func = [] |
First of all, if you do not care about traversing the directory hierarchy recursively, instead of using os.walk, just use os.listdir, as in os.listdir('var/www/html/data/customer/log'). Depending on what you are doing, you may need to filter directories out of the returned list.
If you do care about traversing the structure recursively, then os.walk is what you want, but you need to keep in mind that it yields a (dir, dirs, files) tuples and what you really want is a sequence of file names from files prefixed with dir. This is what my code in #4 is doing. As for “NameError: name 'content' is not defined”, the variable is local to the function, so it cannot be accessed outside of it. What you want is to (a) just get rid of the function and run the code in outer context, or (b) capture return of the function as in “content = list_files()”. |
Many thank you's
I will use option (a) but in better understanding choice (b) content = list_files(), I noticed that accessing the elements in: Code:
content[(0)] Code:
content[(1)] |
“content[2][0]” will access those individual files, but as I described, it is not how you want your function to work.
|
All times are GMT -5. The time now is 12:35 PM. |