file list without hidden files


5 posts
by c7aig » Sat Jun 23, 2012 2:01 pm
Hi,

I am using code like this to print a list of files:

folder=/home/pi/Desktop/
dirList=os.listdir(folder)
for list in dirList:
print list

This is fine but because I am often updating the folder with OSX it keeps showing up .DS_STORE files. Is there a way to exclude anything hidden (with a .)?

Craig
Posts: 2
Joined: Fri Jun 22, 2012 11:51 am
by SN » Sat Jun 23, 2012 2:24 pm
put an if statement inside the for loop and check the first character for a dot?
Steve N – binatone mk4->intellivision->zx81->spectrum->cbm64->cpc6128->520stfm->pc->raspi ?
User avatar
Posts: 1008
Joined: Mon Feb 13, 2012 8:06 pm
Location: Romiley, UK
by andyl » Sat Jun 23, 2012 3:14 pm
SN wrote:put an if statement inside the for loop and check the first character for a dot?


That is one way of doing it.

Better would be

Code: Select all
def isNotHiddenFilename(fname):
    return not fname.startswith(".")
 
folder="/home/pi/Desktop/"
dirList=os.listdir(folder)
nonHiddenFiles= filter(isNotHiddenFilename, dirList)


Even better.you can use list comprehensions
Code: Select all
nonHiddenFiles = [ filename for filename in dirList  if not filename.startsWith(".") ]


Or use filter with a lambda (which will get rid of the small function in the first example
Code: Select all
nonHiddenFiles  = filter(lambda fname: not fname.startswith("."), dirList)


The last two are quite advanced Python though and some people find them hard to read.
Posts: 265
Joined: Tue Jan 10, 2012 11:05 am
by c7aig » Sat Jun 23, 2012 3:33 pm
Hi,

Thanks for the detailed reply, I went with the first option which has given me exactly what I was after :)

Craig
Posts: 2
Joined: Fri Jun 22, 2012 11:51 am
by Joe Schmoe » Sat Jun 23, 2012 3:37 pm
So...

The answer to the question is: No, there isn't. What there are are workarounds/kludges to filter the dot files out of the list, but there's no way to have the list not contain them in the first place.
Never answer the question you are asked. Rather, answer the question you wish you had been asked.

- Robert S. McNamara - quoted in "Fog of War" -
Posts: 2784
Joined: Sun Jan 15, 2012 1:11 pm