...

/

Read/Write Operations

Read/Write Operations

Learn how to read/write data in a file.

We'll cover the following...

Write operations

There are two functions for writing data to a file, as shown below:

Press + to interact
msg = 'Bad officials are elected by good citizens who do not vote.\n'
msgs = ['Humpty\n', 'Dumpty\n', 'Sat\n', 'On\n', 'a\n', 'wall\n']
f = open('message', 'w')
f.write(msg)
f.close()
print('------Reading the file "message"------')
f = open('message', 'r')
data = f.read( )
print(data)
f.close( )
f = open('messages', 'w')
f.writelines(msgs)
f.close()
print('------Reading the file "messages"------')
f = open('messages', 'r')
data = f.read( )
print(data)
f.close( )

Note: We can write a string using the ...