2016-01-23 101 views
0

所以我想在if语句中使用来自文本文件某一行的数据。这就是我所拥有的,即使文本文件的第2行设置为“off”或“on”,也不会发生任何事情。Python - 从文本文件中读取字符串

gamestatus = linecache.getline('C:/directory/gameinfo.txt', 2) 
if gamestatus == 'off': 
    print("Test") 
elif gamestatus == 'on': 
    print("Another test") 

但是,如果我不喜欢的东西 打印(gamestatus) 而不是在一个if语句,它打印“关闭”或“开”。有任何想法吗?

+0

向我们展示一个文本文件的示例 – TisteAndii

回答

0

行cache.getLine返回以文本结尾的行。以下列字符串结束:

gamestatus = linecache.getline('Password.txt', 1).rstrip('\n') 

您可以使用不带参数的rstrip()来删除所有尾随空格。

0
LINE_NUMBER = 2 

with open('C:/directory/gameinfo.txt') as f: 
    for i in range(LINE_NUMBER - 1): 
     f.readline() 
    gamestatus = f.readline().rstrip() 
if gamestatus == 'off': 
    print("Test") 
elif gamestatus == 'on': 
    print("Another test")