Ben Monastyrsky Ben Monastyrsky - 9 months ago 43
Python Question

Not printing correct string

number = int(input('Enter Line: '))
f = open('path.txt','r')
text = f.readline(number)

The file "path.txt" looks like this:




yet, no matter what number you enter, it will still return line1.


You're incorrectly using f.readline(), passing this method a parameter will not return a specific line number. This method always reads and returns the next line (in this case line #1), and your parameter is actually functioning as a substring.

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

I believe the usage you're really looking for is this:

number = int(input('Enter Line: '))
f = open('path.txt','r')
lines = f.readlines()

f.readlines() reads and returns all lines, then you can index.

See live example