A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/os_listdir.htm below:

Python os.listdir() Method

Python os.listdir() Method

The Python os.listdir() method returns a list containing the names of the files within the given directory. The list will be in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

When listdir() is invoked without any arguments, it displays the current working directory.

Syntax

Following is the syntax for Python os.listdir() method −

os.listdir(path)
Parameters

The Python os.listdir() method accepts a single parameter −

Return Value

The Python os.listdir() method returns a list containing the names of the entries in the directory given by path.

Example

The following example shows the usage of listdir() method. Here, we are displaying files and directories available in the path "/home/TP".

import os, sys

# Open a file
path = "/home/TP"
dirs = os.listdir( path )

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

When we run above program, it produces following result −

Desktop
Pictures
Templates
.bash_history
Python
Music
.cache
.bashrc
Documents
Videos
Public
Downloads
.local
Example

In the following example, we are using the listdir() without passing any arguments. It will show the directories of the current working directory.

import os

# Listing only directories from current directory
print("Directories from the current directory:") 
drctry = [item for item in os.listdir() if os.path.isdir(item)]
print(drctry)

On running, the above program will produce the following result −

Directories from the current directory:
['new', 'tmp', 'Tutorials']

python_files_io.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4