Someone
Someone

Reputation: 55

How to read a specific line from a text file in python

I am trying to make a game that requires me to read specific lines from a text (.txt) file in python 3.6. I have figured out a way to do this if I just want to print the line. However, I want to use the line in an if statement: Note* The text file is called 'text' and has '1' on line 1, '2' on line 2 etc etc.

file = open("text.txt", "r")

line1 = file.readline()
line2 = file.readline()
line3 = file.readline()

print(line1)
print(line2)
print(line3)

if line1 == "1":
    print("True")
else:
    print("False")
file.close()

I know that it is reading the lines correctly, because of the print testing. However the if statement is printing false. I don't know what I am doing wrong, and I haven't found anything in my research.

Upvotes: 0

Views: 5516

Answers (3)

Shivid
Shivid

Reputation: 1343

you can do it by pandas skiprows in read_csv as well. suppose your table is like this,

import numpy, pandas, time
my_table = numpy.random.random((10, 4))
numpy.savetxt("text.txt", my_table, delimiter=",")

you can simply read specific line by setting skiprows;

print(pandas.read_csv("text.txt", sep =',',header = None, skiprows =3, nrows = 1))

or assign each line to a variable;

for i in range(len(df)):
     locals()['line'+ str(i+1)] = pandas.read_csv("text.txt", sep =',',header = None, skiprows =i, nrows = 1)
print(line1)

or just the array values:

print(line2.values)

Upvotes: 0

l'L'l
l'L'l

Reputation: 47284

You could convert your string to an integer and check it that way:

if int(line1) == 1:

It might give you more flexibility in the long run...

Upvotes: 0

samu
samu

Reputation: 3120

You're reading your line with the newline character at the end. Your line1 variable probably contains string '1\n'.

Try calling .strip() immediatelly after readline:

line1 = file.readline().strip()
line2 = file.readline().strip()
line3 = file.readline().strip()

Upvotes: 2

Related Questions