Tuesday, 21 September 2021

Python: Create empty file

Open a file in write access mode. To create a file, we should get a file handle in write access mode. Below table summarizes the different access modes supported in python.

 

Access Mode

Description

r

Read only mode. Open a file for reading. It is the default mode, by any chance if the file is not exists, this method raise I/O error.

 

When you open a file using this mode, file handle is positioned at the beginning of the file.

r+

Read and write mode. Open the file to perform both read and write operations. By any chance if the file is not exists, this method raise I/O error.

 

This mode opens an existing file without truncating it.

w

Write only mode. This mode is used to write the content to a file. It creates a file, if the file is not exist.

w+

Read and write mode. Open the file to perform both read and write operations. This mode either creates a file or truncates the existing file.

a

Append only mode. Open the file for appending content. It creates a file, if the file is not exist.

 

That data written to the file is appended to the end.

a+

Append and read mode. It creates a file, if the file is not exist. That data written to the file is appended to the end.

 

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

Find the below working application.

 

create_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)

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