7.6: Letting the user choose the file name

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    7.6: Letting the user choose the file name

    We really do not want to have to edit our Python code every time we want to process a different file. It would be more usable to ask the user to enter the file name string each time the program runs so they can use our program on different files without changing the Python code.

    This is quite simple to do by reading the file name from the user using input as follows:

    fname = input('Enter the file name: ')
    fhand = open(fname)
    count = 0
    for line in fhand:
        if line.startswith('Subject:'):
            count = count + 1
    print('There were', count, 'subject lines in', fname)
    
    # Code: http://www.py4e.com/code3/search6.py

    We read the file name from the user and place it in a variable named fname and open that file. Now we can run the program repeatedly on different files.

    python search6.py
    Enter the file name: mbox.txt
    There were 1797 subject lines in mbox.txt
    
    python search6.py
    Enter the file name: mbox-short.txt
    There were 27 subject lines in mbox-short.txt

    Before peeking at the next section, take a look at the above program and ask yourself, "What could go possibly wrong here?" or "What might our friendly user do that would cause our nice little program to ungracefully exit with a traceback, making us look not-so-cool in the eyes of our users?"


    This page titled 7.6: Letting the user choose the file name was last modified on Tue, 01 Dec 2020 03:50:54 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.