Python os.listdir() method
Python OS file/directory methods
Overview
The os.listdir() method returns a list of the names of files and folders contained in the specified folder.
It does not include '.' and '..' even if they are present in the folder.
Only supported on Unix and Windows.
Note:For cases where a directory contains Chinese subdirectories, Python 2 requires encoding processing, but Python 3 does not; the unicode() method has been removed and the default encoding is utf8, so conversion is needed.
Syntax
The **listdir()** method syntax is as follows:
os.listdir(path)
Parameters
-
path -- The path of the directory to list
Return Value
Returns the list of files and folders under the specified path.
Example
The following example demonstrates the use of the listdir() method:
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
os
,
sys
Opening a File
path
=
"/var/www/html/"
dirs
=
os
.
listdir
(
path
)
Output all files and folders
for
file
in
dirs:
(
file
)
The output of the above program is:
test.htm
stamp
faq.htm
_vti_txt
robots.txt
itemlisting
resumelisting
writing_effective_resume.htm
advertisebusiness.htm
papers
resume
In Python 2, for the case where Chinese names exist in a directory, the directory structure is as follows:

Example
#!/usr/bin/python
-- coding: UTF-8 --
import
os
Opening a File
path
=
"./git-test"
upath
=
unicode
(
path
,
'utf-8'
)
dirs
=
os
.
listdir
(
upath
)
Output all files and folders
for
file
in
dirs:
(
file
)
The output of the above program is:
runoob
runoob-git-test
another-runoob-name
中文目录测试