smarter way of reading from a .txt file (for-loop?)

I'm reading from a .txt file that has one line of text (YPerson18) I'm wondering if there is a smarter way of writing this code preferably using a for loop.

import os

parent_dir = "../dirfiles"

file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"

read_file = open(file_name, read_mode)

the_lines =
print("Initial of the first name is: {}".format(the_lines))

the_lines =
print("The last name is: {}".format(the_lines))

the_lines =
print("The age is: {}".format(the_lines))


How the output should look like:

Initial of the first name is: Y
The last name is: Person
The age is: 18

1 answer

  • answered 2018-11-07 20:37 Barmar

    You could read the whole file into a string variable, then use slice notation to get parts of it.

    with read_file = open(file_name, read_mode):
        line =
        initial = line[0]
        last_name = line[1:7]
        age = int(line[7:])