简体   繁体   English

如何使用 python 测试 txt 文件中的特定行

[英]how to test specific line in the txt file using python

I create txt file that contain three lines我创建包含三行的 txt 文件

hi123
ok
good

and I want to test if the my var is equal to some line in the txt file the first line in my txt file is equal to my var when i print it but the test is give me False like this我想测试我的 var 是否等于 txt 文件中的某行当我打印它时我的 txt 文件中的第一行等于我的 var 但测试给我这样的 False

file = open("copy.txt", "r")
all_lines_variable = file.readlines()
var = 'hi123'
print(all_lines_variable[0], all_lines_variable[0] == var)
file.close()

and the output is output 是

hi123
 False

Because the specific line in your file is not 'hi123' , in fact, it's 'hi123\n' .因为文件中的特定行不是'hi123' ,实际上是'hi123\n' There is a newline at the end.最后有一个换行符。 So you can change your var to 'hi123\n' or try to remove any newline character.因此,您可以将var更改为'hi123\n'或尝试删除任何换行符。

Because there is a line break at the end of the line.因为行尾有一个换行符。 You can see that by the fact that print wrote the contents of var in a new line.您可以通过print在新行中写入var的内容这一事实看到这一点。

If the var contents just have to be in that line, you could use print(all_lines_variable[0], var in all_lines_variable[0]) instead.如果var内容必须在该行中,则可以使用print(all_lines_variable[0], var in all_lines_variable[0])代替。

Otherwise, you could remove the last character of the line (the break) and use it in the comparison like this: print(all_lines_variable[0], all_lines_variable[0][:-1] == var)否则,您可以删除该行的最后一个字符(中断)并在比较中使用它,如下所示: print(all_lines_variable[0], all_lines_variable[0][:-1] == var)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM