Getting Data from a File

Create a text file called name-and-numbers.txt and put a name on the first line and then three numbers (one per line) on the lines below.

gettingfromfile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from __future__ import print_function

def main():
    print("Getting name and three numbers from a file... ", end="")
    with open('name-and-numbers.txt', mode='r') as f:
        name = f.readline().strip()
        a = int(f.readline())
        b = int(f.readline())
        c = int(f.readline())
    print("done.")
    print("Your name is " + name)
    total = a + b + c
    print("{} + {} + {} = {}".format(a, b, c, total))


if __name__ == "__main__":
    main()

What You Should See

Getting name and three numbers from a file... done.
Your name is Samantha Showalter
5 + 6 + 7 = 18

The readline() method reads an entire line from the file and returns it as a string. It has a "\n" at the end, which the .strip() method removes.

Study Drills

  1. Open the text file and change the name or numbers. Save it. Then run your program again.



©2017 Graham Mitchell