2014-02-10 68 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