Python无法将文件的内容与if语句进行比较

时间:2014-02-10 21:52:47

标签: 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.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)

1 个答案:

答案 0 :(得分: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)