By getting the file handle in write mode, we can create an empty file.
Example
with open(os.path.join(path, file_to_create), 'w') as fp:
pass
Find the below working application.
create_empty_file.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)
['Hello World\n', 'Welcome to the world\n']
Writing some content to the file
['test 1\n', 'orld\n', 'Welcome to the world\n']
No comments:
Post a Comment