How to open a file in read and write mode with Python?


To open files in read/write mode, specify 'w+' as the mode. For example,

f = open('my_file.txt', 'w+')
file_content = f.read()
f.write('Hello World')
f.close()

 Above code opens my_file.txt in write mode, stores the file content in file_content variable and rewrites the file to contain "Hello World". You can also use r+ mode as it doesn't truncate the file. 

Updated on: 01-Oct-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements