2014-02-10 102 views
0

好的,所以我有一個名爲cl.DAT的文件,其中包含一種顏色。文件被讀取,然後我將它的內容與改變文本顏色的系統功能相匹配。該文件打開正常,但即使當文件與顏色匹配(我檢查了空白),沒有任何反應。有任何想法嗎?Python無法將文件內容與if語句進行比較

import os 
import time 
color_setting_file = file("cl.dat") 
print "The file says the color is " + color_setting_file.read() 

if str(color_setting_file.read()) == "blue": 
     os.system('color 9') 
     print "set blue" 
if str(color_setting_file.read()) == "green": 
     os.system('color a') 
     print "set green" 
if str(color_setting_file.read()) == "white": 
     os.system('color 7') 
     print "set white" 
if str(color_setting_file.read()) == "red": 
     os.system('color 4') 
     print "set red" 
if str(color_setting_file.read()) == "yellow": 
     os.system('color 6') 
     print "set yellow" 
if color_setting_file.read() == "pink": 
     os.system('color 47') 
     print "set pink" 
else: 
     print("None of the above.") 
time.sleep(10) 

回答

2

您應該將color_setting_file.read()的結果存儲在一個變量中,並檢查而不是多次調用它。

現在,您從color_setting_file.read()開始返回一個空字符串,因爲文件已到達。 See the python docs

如:

import os 
import time 
color_setting_file = file("cl.dat") 
color = color_setting_file.read() 
print "The file says the color is " + color 

if str(color) == "blue": 
     os.system('color 9') 
     print "set blue" 
if str(color) == "green": 
     os.system('color a') 
     print "set green" 
if str(color) == "white": 
     os.system('color 7') 
     print "set white" 
if str(color) == "red": 
     os.system('color 4') 
     print "set red" 
if str(color) == "yellow": 
     os.system('color 6') 
     print "set yellow" 
if str(color) == "pink": 
     os.system('color 47') 
     print "set pink" 
else: 
     print("None of the above.") 
time.sleep(10) 
+1

這解決了我的問題。謝謝您的幫助! – user3161223