Python从文本Fi读取字符串

2024-10-03 15:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想在if语句中使用文本文件中某一行的数据。这就是我所拥有的,即使文本文件的第2行设置为“off”或“on”,也不会发生任何事情。你知道吗

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

但是,如果我做了 打印(游戏状态) 但不是在if语句中,它打印“off”或“on”。有什么想法吗?你知道吗


Tags: 数据testtxtifon语句事情directory
2条回答

线路缓存.getLine返回以文本结尾的行。把结尾的线串起来,像这样:

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

可以使用不带参数的rstrip()删除所有尾随空格。你知道吗

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") 

相关问题 更多 >