Python 2.7 如何在python中结束while循环?

Python 2.7 如何在python中结束while循环?,python-2.7,Python 2.7,我有一个简单的习惯,永不放弃 import sys infile = sys.argv[1] outfile = sys.argv[2] count=1 print 'Input file is ', infile print 'Output file is ', outfile instream = open(infile,'r') while True: line=instream.readline() if line[0:5]=='<?xml':

我有一个简单的习惯,永不放弃

 import sys
 infile = sys.argv[1]
 outfile = sys.argv[2]
 count=1
 print 'Input file is ', infile
 print 'Output file is ', outfile
 instream = open(infile,'r')
 while True:
     line=instream.readline()
     if line[0:5]=='<?xml':
     print 'new record', count
     count=count+1
     if line == "eof":
         print 'end'
         break
导入系统 infle=sys.argv[1] outfile=sys.argv[2] 计数=1 打印“输入文件为”,填充 打印“输出文件为”,输出文件 河道内=开阔(填充,'r') 尽管如此: 行=流内读取行() 如果第[0:5]行=='
readline()
没有返回表示文件结束的字符串
eof
;它返回空字符串。(注意
readline
保留了终止每一行的换行符,因此空行将表示为
'\n'
;因此真正的空行只能表示没有留下任何数据。)

你可以写

但通常您只是将文件视为迭代器:

for line in instream:
    if line[0:5] == '<?xml':
        print 'new record', count
        count = count + 1
用于流内管线:
如果行[0:5]='
for line in instream:
    if line[0:5] == '<?xml':
        print 'new record', count
        count = count + 1