Search⌘ K
AI Features

Read/Write Operations

Explore basic file input and output operations in Python including writing strings and lists to files and reading entire files or line-by-line. Understand how to handle file objects and manage data conversion for writing non-string objects.

We'll cover the following...

Write operations

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

Python 3.8
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 write() ...