Read and Write File with Python

Adi Ramadhan
1 min readSep 4, 2020

--

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())
file.close()

‘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.

--

--

Adi Ramadhan
Adi Ramadhan

No responses yet