c7aig
Posts: 2
Joined: Fri Jun 22, 2012 11:51 am

file list without hidden files

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

User avatar
SN
Posts: 1012
Joined: Mon Feb 13, 2012 8:06 pm
Location: Romiley, UK
Contact: Website

Re: file list without hidden files

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 ?

andyl
Posts: 265
Joined: Tue Jan 10, 2012 11:05 am

Re: file list without hidden files

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.

c7aig
Posts: 2
Joined: Fri Jun 22, 2012 11:51 am

Re: file list without hidden files

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

Joe Schmoe
Posts: 4277
Joined: Sun Jan 15, 2012 1:11 pm

Re: file list without hidden files

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.
And some folks need to stop being fanboys and see the forest behind the trees.

(One of the best lines I've seen on this board lately)

Return to “Python”

Who is online

Users browsing this forum: No registered users and 13 guests