Read and Write Text Files in Python

Python has a built-in function to open, read, and write files.

The open() function opens a file and return it as a file object.

Read Text File

The file object in Python has a readlines() method which can be used to read contents of text files.

Example

file_not_found = False
try:
    file = "test.txt"
    with open(file) as tf:
        lines = tf.readlines()
        for line in lines:
            print(line)
except FileNotFoundError as ex:
    print("Error reading file : " + str(ex))
    file_not_found = True
finally:
    if not file_not_found:
        print("Closing file...")
        tf.close()

Write To Text files

The file object in Python has a writelines() method which can be used to write in text files.

Example

file_not_found = False
try:
    file = "test.txt"
    with open(file, mode='w') as tf:
        lines = ["This is first line.\n", "This is second line.\n", "This is third line.\n"]
        tf.writelines(lines)
except FileNotFoundError as ex:
    print("Error writing to file : " + str(ex))
    file_not_found = True
finally:
    if not file_not_found:
        print("Closing file...")
        tf.close()