簡體   English   中英

Python-從文本文件讀取字符串

[英]Python - Read Strings from Text File

所以我想在if語句中使用文本文件中特定行的數據。 這就是我所擁有的,即使文本文件的第2行設置為“關閉”或“打開”,也沒有任何反應。

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

但是,如果我執行了諸如print(gamestatus)之類的操作,但未在if語句中進行操作,則會打印“ off”或“ on”。 有任何想法嗎?

行cache.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") 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM