Ben Monastyrsky Ben Monastyrsky - 3 months ago 6
Python Question

Not printing correct string

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


The file "path.txt" looks like this:

line1

line2

line3

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

Answer

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. https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

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

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

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

See live example