[英]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. 我正在尝试制作一个游戏,要求我从python 3.6的文本(.txt)文件中读取特定行。 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.
但是,我想在if语句中使用该行:注意*文本文件称为“文本”,在第1行上具有“ 1”,在第2行上具有“ 2”,依此类推。
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.
但是,if语句显示为false。 I don't know what I am doing wrong, and I haven't found anything in my research.
我不知道自己在做错什么,在研究中也没有发现任何东西。
You're reading your line with the newline character at the end. 您正在阅读结尾处带有换行符的行。 Your
line1
variable probably contains string '1\\n'
. 您的
line1
变量可能包含字符串'1\\n'
。
Try calling .strip()
immediatelly after readline: 尝试在
.strip()
之后立即调用.strip()
:
line1 = file.readline().strip()
line2 = file.readline().strip()
line3 = file.readline().strip()
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... 从长远来看,它可能会给您带来更大的灵活性。
you can do it by pandas skiprows
in read_csv
as well. 您可以通过熊猫做
skiprows
在read_csv
为好。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.