Python可以';t比较文件';包含if语句的内容

Python可以';t比较文件';包含if语句的内容,python,file,colors,Python,File,Colors,好的,我有一个名为cl.DAT的文件,它包含一种颜色。文件被读取,然后我将其内容与更改文本颜色的系统函数相匹配。文件可以正常打开,但即使文件与颜色匹配(我检查了空白),也不会发生任何事情。有什么想法吗 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.

好的,我有一个名为cl.DAT的文件,它包含一种颜色。文件被读取,然后我将其内容与更改文本颜色的系统函数相匹配。文件可以正常打开,但即使文件与颜色匹配(我检查了空白),也不会发生任何事情。有什么想法吗

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)

您应该将
color\u setting\u file.read()
的结果存储在变量中并进行检查,而不是多次调用它

照原样,您将从
color\u setting\u file.read()
返回一个空字符串,因为已到达文件末尾

例如:

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)