Python3 os.listdir() Method
Python3 OS File/Directory Methods
Overview
The os.listdir() method is used to return a list of names of files or folders contained in the specified folder. This list is in alphabetical order. It does not include.and..even if it is in the folder.
Only supported on Unix and Windows.
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
#!/usr/bin/python3
import os, sys
# Open file
path = "/var/www/html/"
dirs = os.listdir( path )
# Output all files and folders
for file in dirs:
print (file)
import os, sys
# Open file
path = "/var/www/html/"
dirs = os.listdir( path )
# Output 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
If the directory contains Chinese, no special handling is required; it will be output normally because Python3 defaults to UTF-8 encoding. The directory structure is as follows:

Example
#!/usr/bin/python-
import os
# Open file
path = "./git-test"
upath = unicode(path,'utf-8')
dirs = os.listdir( upath )
# Output all files and folders
for file in dirs:
print (file)
import os
# Open file
path = "./git-test"
upath = unicode(path,'utf-8')
dirs = os.listdir( upath )
# Output 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