Skip to main content

Command Palette

Search for a command to run...

Random Quote

Introducing file reading

Published
3 min readView as Markdown
Random Quote
A

Corporate trainer

In this post we will see how to display a random quote on the console. Every time you run the code, a different quote appears.

We will read the quotes from a file. We have multiple files and each file contains a bunch of quotes, one on each line

Directory structure

We will structure our app as follows.

app-root
  files
    Eckhart_Tolle.txt
    J_Krishnamurti.txt
  app.py

As you can see, the program app.py is in the root folder (anywhere in the file system). In the same folder, you will create a folder called files which will contain text files. Each file is named with author's name and contains that author's quotes one per line.

We will need two modules in our program

  • os for locating the path of the files
  • random for randomly picking an author and their quote, also picked randomly.

Given the path, the os module function listdir() retrieves a list of files.

From each file in the list we will retrieve the author's name from the file name. It will be of the form author_name.txt.

Dictionary

We will then build a dictionary with author names for keys and a list of quotes for values.

The dictionary that we are going to build will be of the form:

d = {'a1':['q1', 'q2','q3'], 'a2':['q1','q2','q3']

Random

This scheme allows us to randomly select authors and a quotation from their list of quotes.

We will use the random.choice() function to select one item from multiple options.

The Program

The main() function fetches the list of files. It needs two helper functions to run the program:

  • get_author_names(file_list) to retrieve author names from file names
  • get_quotes_dict(author_names, file_list) to associate authors with their quotes

File reading

The function open() is used to open and read files and directories in the file system. It follows the syntax:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

It has several parameters. The file is of course required. It will throw an error if the file is not found at the path specified or it is not permitted to read. We have skipped the error handling and is left as an exercise to the developer.

We have specified 'r' mode for opening the file to read. We have also specified the Unicode encoding UTF-8, which is equivalent to the ASCII character set, since it is all in English only.

Here's the program in its entirety.

import os
import random

# store author names from file names (filename = author_name.txt)
def get_author_names(file_list):
    author_names = []
    for file in file_list:
        # get the name part
        path_tokens = file.split('\\')
        file_name = path_tokens[-1]
        # remove .txt from file name to get the author name
        file_name = file_name.split('.')[0]
        # remove underscore from author name
        file_name = file_name.replace("_", " ")
        author_names.append(file_name)
    return author_names

# build a dictionary of authors and their quotes of the form
# d = {'a1':['q1', 'q2','q3'], 'a2':['q1','q2','q3']} 
def get_quotes_dict(authors, files):
    # read files and store data
    quotes = {}
    # fetch authors
    author_files = list(zip(authors, files))
    # build quotes dictionary, created empty above
    for item in author_files:
        name, file_ = item
        f = open(os.getcwd()+'/files/'+file_, 'r', encoding='utf8')
        quotes[name] = f.readlines()
    return quotes

def main():
    file_list = os.listdir('./files')
    author_names = get_author_names(file_list)
    quotes = get_quotes_dict(author_names, file_list)
    # display random quote from random author
    r_author = random.choice(author_names)
    r_quote = random.choice(quotes[r_author])
    print("\n" + r_quote)
    print("\t" + r_author + "\n")


if __name__ == '__main__':
    main()

Exercise

  • Take input from the user for the name of the author.
  • Give options to choose author name.
  • Display a random quote from that author.

Enjoy coding with your own quotations!