Tuesday, 21 September 2021

Python: Create and write content to a file

By getting the file handle in write mode, we can create and write to the file.

 

Example

with open(os.path.join(path, file_to_create), 'w') as fp:    
    fp.write("Test line 1\n")
    fp.write("Test line 2")

 

Find the below working application.

 

create_and_write_to_file.py

import os

file_to_create = 'myfile.txt'

path = '/Users/Shared/data'
files_in_path = os.listdir(path) 

with open(os.path.join(path, file_to_create), 'w') as fp:    
    fp.write("Test line 1\n")
    fp.write("Test line 2")

with open(os.path.join(path, file_to_create), 'r') as fp:    
    file_content = fp.readlines()
    print(file_content)

 

Output

['Test line 1\n', 'Test line 2']

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment