Easy Tutorial
❮ Python String Isalpha Python Assert ❯

Python3 os.listdir() Method

Python3 OS File/Directory Methods


Overview

The os.listdir() method is used to return a list of the names of the files or directories contained in the specified folder. This list is sorted alphabetically. It does not include . and .. even if they are present in the directory.

This method is supported on Unix and Windows systems.

Syntax

The syntax for the listdir() method is as follows:

os.listdir(path)

Parameters

Return Value

Returns a list of files and directories in the specified path.

Example

The following example demonstrates the use of the listdir() method:

#!/usr/bin/python3

import os, sys

# Open file
path = "/var/www/html/"
dirs = os.listdir(path)

# Print all files and directories
for file in dirs:
    print(file)

Executing the above program outputs the following:

test.htm
stamp
faq.htm
_vti_txt
robots.txt
itemlisting
resumelisting
writing_effective_resume.htm
advertisebusiness.htm
papers
resume

Handling Chinese characters in the directory does not require special treatment and can be output normally, as Python3 uses UTF-8 encoding by default. The directory structure is as follows:

#!/usr/bin/python

import os

# Open file
path = "./git-test"
upath = unicode(path, 'utf-8')
dirs = os.listdir(upath)
# Print all files and directories
for file in dirs:
    print(file)

Executing the above program outputs the following:

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

Python3 OS File/Directory Methods

❮ Python String Isalpha Python Assert ❯