Python如果变量中的变量

时间:2016-09-27 17:35:45

标签: python file filereader

我已将文件调用helloworld.simon。 在那里我写了:

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

2 个答案:

答案 0 :(得分: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),则输出J

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