Skip to content Skip to sidebar Skip to footer

How To Print A Specific Line From A File

I am trying to print a specific line from the file 'Scores', which is option B. This is my code: print('Option A: Show all scores\nOption B: Show a record\nOption Q: Quit') decisio

Solution 1:

A few cents from my side :

file = open("file")
lines = file.readlines()
for line inlines:
    if playername in line:
        print line

file.close()

Hope it works!

Solution 2:

find() method returns a positive index if it succeeds, -1 otherwise

You should loop on your content line by line, as follows:

for line in myFile:
    if line.find(playerName):
        print(line)

Solution 3:

A safer way to read the file and find data, so that you will not have OutOfMemory issues when storing the whole file in memory.

playerName = input("Enter a player name to view their scores: ")
withopen("Scores.txt", 'r') as f:
    for row in f:
        if playerName in row:
            print row

This way you will be using with that will close the file by itself either when the program ends or Garbage Collection kicks in. This way python will read the file line by line and store only 1 line in memory. So you can use huge files and do not worry about memory issues.

Hope it helps :)

Solution 4:

Working with str methods will take more acrobatics. Try the following,

import re
p = re.compile(r"\b{}\b".format(playername)) # keep it ready# inside option Bfor line in myfile:    # no need to `.read()` it
    match = p.search(line)
    if match:
        print(line)
        break# if there is only one record for playername

See if it works for you.

Solution 5:

similar thing here: Reading specific lines only (Python)

fp = open("file")
for i, line in enumerate(fp):
    if line == playername:
        print line

fp.close()

I also notice you don't close your file for each decision, should make that happen.

Post a Comment for "How To Print A Specific Line From A File"