user3533193
user3533193

Reputation: 11

How to read specific characters in python 2.7.6 in a specific line?

Suppose I have this text written in line number 5

" Name: Roger Federer

how can I go to line number 5 first and then read and print out "Roger Federer" instead of the whole line.I am not getting how to use the file.seek function in this case.

Upvotes: 1

Views: 442

Answers (2)

alecxe
alecxe

Reputation: 474081

Instead of loading the entire file into memory using readlines() (just for reading the single 5-th line), iterate over the file object line-by-line and stop (break) on the 5-th line:

with open('input.txt', 'r') as f:  
    for number, line in enumerate(f):
        if number == 4:
            print(line.split(':')[-1].strip())
            break

Note: getting Roger Federer out of " Name: Roger Federer by splitting the string by : and getting the last element, strip() helps to omit new-lines and unwanted leading and trailing spaces:

>>> line = " Name: Roger Federer"
>>> print(line.split(':')[-1].strip())
Roger Federer

Upvotes: 0

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18467

I wouldn't use file.seek here since it takes bytes as an argument. Just use what you know:

with open('somefile.txt', 'r') as somefile:
    lines = somefile.readlines()

roger_federer_line = lines[4]   # 5th line
print(roger_federer_line[6:])   # print 6th character onwards

This assumes your file line says Name: Roger Federer. If it has " at the beginning of the line you should use 8 instead of 6.

Upvotes: 3

Related Questions