简体   繁体   中英

Python - Read Strings from Text File

so I want to use data from a certain line of a text file in an if statement. This is what I have, and even if line 2 of the text file is set to 'off' or 'on', nothing happens.

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

But, if I did something like print(gamestatus) but not in a an if statement, it prints 'off' or 'on'. Any ideas?

Line cache.getLine returns the line ending along with the text. String the line ending off like:

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

You can use rstrip() without args to remove all trailing whitespace.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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