所以我有这个.txt文件,每行有100多行和一个值
我如何读取特定行的值并将其用于if?
让我们说我想读取第34行,看看该行的值是0还是1。我真的不知道如何解释但我正在考虑这样的事情。我可以分配" print(第34行)和#34;一个整数,然后将整数与0或1进行比较?请记住,我没有使用python的经验。
f = open("NT.txt",'r')
lines = f.readlines()
if print(lines[34]) == 1:
print("something")
答案 0 :(得分:2)
if lines[34].strip() == "1":
因为文件总是文字......可能会回答你的问题吗?
(请注意,因为列表以0 lines[34]
开头是第35行)
if int(lines[34])==1:
您听说print
而不是int
答案 1 :(得分:1)
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.
答案 2 :(得分:0)
This should work:
f=open('NT.txt', 'r')
lines=f.readlines()
if int(lines[34])==1:
print('something')