os.listdir() showing file actually not in the folder on Python and Windows

5.8k views Asked by At

The following Python script:

import os
print os.listdir('D:\images')

is outputing the names of all the folders in the D:\image directory, but it is also showing desktop.ini in the same folder, while there is no such file in the image directory.

Its also not a hidden item, I am sure of that.

Why is it then showing it as a content?

2

There are 2 answers

4
Vlad On BEST ANSWER

desktop.ini is a protected system file, and Windows tends to hide it.

You can verify by going to D:\images in a terminal and running dir /A.

See this answer as well.

You can use os.walk() if you want more control, it will give you directories and files separately. You can also use os.path.isdir() to find out if an entry you get is a directory.

0
Nancy On

I used os.path.isdir(path) to check whether the item returned by os.listdir() is a directory or not

This way,desktop.ini didn't meet the criteria of being a directory and my program scanned all the folders.