Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 os.listdir() Method

Python3 os.listdir() Method

Python3 OS File/Directory Methods Python3 OS File/Directory Methods


Overview

The os.listdir() method returns a list of the names of files or folders contained in the specified directory. The list is in alphabetical order. It does not include . and .. even if they are in the directory.

Only supported on Unix and Windows.

Syntax

The **listdir()** method syntax is as follows:


os.listdir(path)

Parameters

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/python3

import

os

,

sys

Opening a File

path

=

"/var/www/html/"

dirs

=

os

.

listdir

(

path

)

Output all files and folders

for

file

in

dirs:

   

print

(

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

Chinese characters in directory names need no special handling and are output normally, because Python3 uses utf8 encoding by default. The directory structure is as follows:

Example

#!/usr/bin/python-

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:

   

print

(

file

)

The output of the above program is:

runoob
runoob-git-test
another-runoob-name
中文目录测试

Python3 OS File/Directory Methods Python3 OS File/Directory Methods