Tuesday 21 September 2021

Python: pass keyword: execute nothing

In Python, ‘pass’ keyword is used to execute nothing.

 

Example

with open(os.path.join(path, file_to_create), 'w') as fp:
    pass

 

In the above snippet, I just want to create an empty file and do nothing after that. I used ‘pass’ keyword to achieve this.

 

Find the below working application.

 

pass_1.py

import os

file_to_create = 'myfile.txt'

path = '/Users/Shared/data'
files_in_path = os.listdir(path) 
print("List of directories and files before creating ", file_to_create)
print(files_in_path)

with open(os.path.join(path, file_to_create), 'w') as fp:
    pass

files_in_path = os.listdir(path) 
print("List of directories and files after creating ", file_to_create)
print(files_in_path)

 

Output

List of directories and files before creating  myfile.txt
['test', 'db']
List of directories and files after creating  myfile.txt
['test', 'db', 'myfile.txt']

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment