Read and Write File with Python

Basic read and write file with python 3.x.

Photo by Beatriz Pérez Moya on Unsplash

test.txt

This is first line content.
This is second line content.
This is third line content.

Open and Read Files

file = open('test.txt', 'r')
print(file.read())

‘r’ means read, it is default value, we can use file = open(‘test.txt’) as well . use file.close() to close file.

output:

This is first line content.
This is second line content.
This is third line content.

Write/Create File

f = open('test2.txt', 'w')
f.write('This is line content.')
f.close()

‘w’ means create new or overwrite file content. We can use ‘a’ for append in the end of file content.

Software Engineer