Python os.listdir() Method
Python OS File/Directory Methods
Overview
The os.listdir() method is used to return a list of the names of files or folders contained in the specified folder.
It does not include.and..even if it is in the folder.
It is only supported on Unix and Windows.
Note:For cases where there are Chinese directories under the directory, Python 2 requires encoding processing, but in Python 3 it is not needed; there is no longer a unicode() method, and the default is UTF-8 encoding, so conversion is needed.
Syntax
listdir()The method syntax is as follows:
os.listdir(path)
Parameters
path-- The directory path to be listed
Return Value
Returns a list of files and folders under the specified path.
Example
The following example demonstrates the use of the listdir() method:
Example
# -*- coding: UTF-8 -*-
import os, sys
# Open file
path = "/var/www/html/"
dirs = os.listdir( path )
# Print all files and folders
for file in dirs:
print (file)
The output of running the above program is:
test.htm stamp faq.htm _vti_txt robots.txt itemlisting resumelisting writing_effective_resume.htm advertisebusiness.htm papers resume
For the Python 2 version, in cases where there are Chinese characters in the directory, the directory structure is as follows:

Example
# -*- coding: UTF-8 -*-
import os
# Open file
path = "./git-test"
upath = unicode(path,'utf-8')
dirs = os.listdir( upath )
# Print all files and folders
for file in dirs:
print (file)
The output of running the above program is:
example example-git-test another-example-name 中文目录测试Other Extensions