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"
os.chdir(parent_dir)

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

read_file = open(file_name, read_mode)

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

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

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

read_file.close()

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 = read_file.read().strip()
        initial = line[0]
        last_name = line[1:7]
        age = int(line[7:])