Writing Text Files

Text Files

Broadly speaking, there are two types of files: text files and binary files. A text file stores words and numbers as human readable text. A binary file stores pictures, diagrams, sounds, music, movies, and other media as numbers in a format that is not directly readable by humans.

Writing into a Text File

In order to write text to a file, a program must call the built-in open function to open the file for writing or appending text and then call the .write method or the built-in print function. Example 1 contains a program that asks the user for an inspirational quote and then appends that quote to a text file. At line 8, the program calls the built-in open function, and at line 11, the program calls the built-in print function.


# Example 1

def main():
    # Ask the user to enter a quote.
    quote = input("Please enter an inspirational quote: ")

    # Open the quotes.txt file for appending text.
    with open("quotes.txt", "at") as quotes_file:

        # Print the quote to the text file.
        print(quote, file=quotes_file)


# Call main to start this program.
if __name__ == "__main__":
    main()

Example 2 shows how to write the contents of a list into a text file. At line 21, the program calls the built-in open function to open a text file for writing. At lines 25–26, the program uses a for loop to print each element of a list on a separate line.


# Example 2

def main():
    # Create a list that contains types of small boats.
    boat_list = ["canoe", "kayak", "skiff", "dinghy"]

    # Write the list to a file named small_boats.txt
    write_list("small_boats.txt", boat_list)


def write_list(filename, text_list):
    """Write the contents of a list into a text file.

    Parameters
        filename: the name of the text file to write
        text_list: the list to write to the text file
    Return: nothing
    """
    # Open the text file for writing and store a reference
    # to the opened file in a variable named text_file.
    with open(filename, "wt") as text_file:

        # Print the contents of the list into
        # the text file, one line at a time.
        for element in text_list:
            print(element, file=text_file)


# Call main to start this program.
if __name__ == "__main__":
    main()

CSV Files

Many computer systems import and export data in CSV files. CSV is an acronym for comma separated values. A CSV file is a text file that contains tabular data with each row on a separate line of the file and each cell (column) separated by a comma. The following example shows the contents of a CSV file named hymns.csv that stores data about religious songs. Notice that the first row of the file contains column headings, the next four rows contain data about four hymns, and each row contains three columns separated by commas.

Title,Author,Composer
O Holy Night,John Dwight,Adolphe Adam
"Oh, Come, All Ye Faithful",John Wade,John Wade
Joy to the World,Isaac Watts,George Handel
With Wondering Awe,Anonymous,Anonymous

Python has a standard module named csv that includes functionality to read from and write to CSV files.

Writing a Compound List into a CSV File

Example 3 shows how to write the contents of a compound list into a CSV file. At line 35, the program calls the built-in open function to open a text file for writing. At line 39, the program uses the csv module to create a csv.writer object. At lines 47–48, the program uses a for loop and the csv.writer object to write each row to the CSV file.


# Example 3

import csv

def main():
    heading_list = ["Title", "Author", "Composer"]

    # Create a compound list of hymns.
    hymns_list = [
        ["O Holy Night", "John Dwight", "Adolphe Adam"],
        ["Oh, Come, All Ye Faithful", "John Wade", "John Wade"],
        ["Joy to the World", "Isaac Watts", "George Handel"],
        ["With Wondering Awe", "Anonymous", "Anonymous"]
    ]

    # Call the write_compound_list function which will
    # write the list of hymns to a file named "hymns.csv".
    write_compound_list("hymns.csv", hymns_list, heading_list)


def write_compound_list(filename, compound_list,
        heading_list=None):
    """Write the contents of a compound list into a CSV file.

    Parameters
        filename: the name of the CSV file to write
        compound_list: the list to write to the CSV file
        heading_list: a list that contains the column headings.
            If heading_list is None, this function will not
            write headings to the CSV File.
    Return: nothing
    """
    # Open the text file for writing and store a reference
    # to the opened file in a variable named csv_file.
    with open(filename, "wt", newline="") as csv_file:

        # Use the csv module to create a writer object
        # that will write to the opened CSV file.
        writer = csv.writer(csv_file)

        # Write the heading_list to the CSV file.
        if heading_list is not None:
            writer.writerow(heading_list)

        # Write the contents of the list into
        # the CSV file, one row at a time.
        for row_list in compound_list:
            writer.writerow(row_list)


# Call main to start this program.
if __name__ == "__main__":
    main()

Writing a Dictionary into a CSV File

Example 4 shows how to write the contents of a dictionary into a CSV file. At line 46, the program calls the built-in open function to open a text file for writing. At line 50, the program uses the csv module to create a csv.writer object. At lines 59–77, the program uses a for loop and the csv.writer object to write each row to the CSV file.


# Example 4

import csv

def main():
    heading_list = ["I-Number", "Name"]

    # Create a dictionary that contains student
    # I-Numbers and names.
    students_dict = {
        # I-Number : Name
        "751766201" : "James Smith",
        "751762102" : "Esther Einboden",
        "052058203" : "Cassidy Benavidez",
        "323021604" : "Joel Hatch",
        "251041405" : "Brianna Ririe",
        "001152306" : "Stefano Hisler",
        "182706207" : "Hyeonbeom Park",
        "124712708" : "Maren Thomas",
        "212505409" : "Tyler Clark"
    }

    # Call the write_dict function which will write
    # the students dictionary file named "students.csv".
    write_dict("students.csv", students_dict, heading_list, 0)


def write_dict(filename, dictionary, heading_list=None,
        key_column_index=None):
    """Write the contents of a dictionary into a CSV file.

    Parameters
        filename: the name of the CSV file to write
        dictionary: the dictionary to write to the CSV file
        heading_list: a list that contains the column headings.
            If heading_list is None, this function will not
            write headings to the CSV File.
        key_column_index: the index of the column in the CSV
            file where this function should write the keys.
            If key_column_index is None, this function will
            not write the keys to the CSV file.
    Return: nothing
    """
    # Open the text file for writing and store a reference
    # to the opened file in a variable named csv_file.
    with open(filename, "wt", newline="") as csv_file:

        # Use the csv module to create a writer object
        # that will write to the opened CSV file.
        writer = csv.writer(csv_file)

        # Write the heading_list to the CSV file.
        if heading_list is not None:
            writer.writerow(heading_list)

        # Get each key value pair from the dictionary
        # and write each pair on a separate row in thee
        # CSV file.
        for key, value in dictionary.items():

            # If a value stored in the dictionary is a
            # list, make a temporary copy of that value.
            # Otherwise, create a list that contains the
            # value.
            if isinstance(value, list):
                row_list = value.copy()
            else:
                row_list = [value]

            # If key_column_index is an integer, insert
            # the key into the row_list so that this
            # function will write the key to the CSV file.
            if key_column_index is not None:
                row_list.insert(key_column_index, key)

            # Write a row to the CSV file.
            writer.writerow(row_list)


# Call main to start this program.
if __name__ == "__main__":
    main()

Summary

A text file stores words and numbers as human readable text. To write text into file, your program must first open the file by calling the built-in open function. You should write the code to open a file in a Python with block because the computer will automatically close the file when the with block ends, and you won’t need to remember to write code to close the file. To write text to an open text file, your program can call the built-in print function with the file named argument.

A CSV file is a text file that contains rows and columns of data. CSV is an acronym that stands for comma separated values. Within each row in a CSV file, the data values are separated by commas. Python includes a standard module named csv that helps us easily write Python code to write to a CSV file.