2016-09-27 78 views
-1

我做了一个文件叫helloworld.simon。 在那里,我已经写了:Python如果变量变量

Public class helloworld { 
main = (main.method()); 
main { 
    console.print("Hello World"); 
    } 

而且我写了这个代码:

Public = ("Public") 
Private = ("Private") 
code = open('helloworld.simon' , 'r') 
print(code.read()) 
if Public in code: 
    print("Pub") 
else: 
    print("J") 

输出是:

Public class helloworld { 
main = (main.method()); 
main { 
    console.print("Hello World"); 
    } 

J 
+1

什么是你的问题? –

+0

它打印'J'这就是问题傻!大声笑 – andre3wap

+1

提示:'in'应该用于字符串对象,而不是文件对象。 – Kevin

回答

0

改变这一行:

code = open('helloworld.simon' , 'r')

要这样:

with open('helloworld.simon' , 'r') as f: 
    lines = f.readlines() 
    if any([line for line in lines if Public in line]): 
     print("Pub") 
    else: 
     print("J") 
+1

这仍然打印“J”,不是吗? '[Public class helloworld {\ n“,...]]中的”Public“仍然评估为False。 – Kevin

+0

@Kevin这不打印“J” –

+0

奇怪的是,它在我的机器上打印“J”。 (顺便说一下,我不是那个downvoted的) – Kevin

1

文件读取是连续的。一旦你读一个文件(print(code.read())你不能再回来读,除非重新阅读与code.seek(0)

Public = ("Public") 
Private = ("Private") 
code = open('helloworld.simon' , 'r') 
print(code.read()) 
code.seek(0) 
if Public in code.read(): 
    print("Pub") 
else: 
    print("J") 
code.close() 

输出:

Pub 

如果你对此有何评论code.seek(0),输出Ĵ