Reputation: 55
So I have this .txt file that has over 100 lines and a value on each one.
How would I read the value from a specific line and use it in an if?
Let's say I want to read the line 34 and see if the line has the value 0 or 1 in it. I don't really know how to explain but i was thinking about something like this. would I be able to assign "print(lines[34])" an integer and then compare the integer with 0 or 1? please keep in mind that i have no experience with python.
f = open("NT.txt",'r')
lines = f.readlines()
if print(lines[34]) == 1:
print("something")
Upvotes: 1
Views: 1570
Reputation: 3813
As @JoranBeasley pointed out to my solution in the comment up there, anything read in from a text file is read in as...text (duh!). It would need to be converted to an int, so the proper if
statement should be:
if int(lines[34].strip()) == 1:
# Do something here.
Additionally, most folks would probably open the text file using a with
statement, so that it closes automagically when you're done using it:
with open('NT.txt', 'r') as f:
lines = f.readlines()
if int(lines[34].strip()) == 1:
# Do something here.
Upvotes: 1
Reputation: 86
This should work:
f=open('NT.txt', 'r')
lines=f.readlines()
if int(lines[34])==1:
print('something')
Upvotes: 0
Reputation: 114108
if lines[34].strip() == "1":
since files are always text ... might answer your question?
(note that since lists start with 0 lines[34]
is the 35th line)
of coarse someone may have told you to try
if int(lines[34])==1:
and you heard print
instead of int
Upvotes: 2