Read and Write Files in Python

Python provides a inbuilt way to read and write files. User dont need to import or add new libraries.

Syntax:

file_object = open(filename, mode)
.
.
file_operations
.
.
file_object.close()

Modes

‘r’ : Opens a file for reading only.
‘w’ : Opens a file for only writing
‘a’ : Opens a file for appending; any data written to the file is automatically
added to the end.
‘r+’: Opens a file for both reading and writing.

Read Text from File

file = open('hello.txt','r')
str = file.read()
print(str)
file.close()

Write Text to File

file = open("newfile.txt", "w")
file.write("First Line\n")
file.write("Second Line\n")
file.write("One More Line\n")
file.close()

Leave a Reply

Your email address will not be published. Required fields are marked *