To read data in a file, we use the built-in open( ) function by providing the name of the file as the first argument and the letter ‘r’ as the second argument. To start, we can create a text file as below:

 

# data.txt

In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available.

 

To read data in this text file, we can write a small program as below:

 

with open('data.txt', 'r') as f:
    data = f.read()
    print(data)

 

To write or append new data to a file, we use the same open( ) function by providing the second argument as ‘a’ to append new data and ‘w’ to write new data to the file.

 

with open('data.txt', 'w') as f:
    data = 'some data to be written to the file'
    f.write(data)

 

When we use open( ) function to write data to a file, if that file does not exist, this function will create a new file with the same name.