+ -
当前位置:首页 → 问答吧 → 关于for语句中使用文件对象

关于for语句中使用文件对象

时间:2010-12-08

来源:互联网

import sys

# open file
try:
   file = open( "clients.dat", "r" )
except IOError:
   print >> sys.stderr, "File could not be opened"
   sys.exit( 1 )
   
records = file.readlines()   # retrieve list of lines in file

print "Account".ljust( 10 ),
print "Name".ljust( 10 ),
print "Balance".rjust( 10 )

for record in records:          # format each line
   fields = record.split()
   print fields[ 0 ].ljust( 10 ),
   print fields[ 1 ].ljust( 10 ),
   print fields[ 2 ].rjust( 10 )

file.close()

    这是我阅读的教程中的一个例题,有一个问题:
           文中说允许在for语句中使用文件对象, for record in records 可以替换为 for record in file,可以达到相同的效果而且更高效,但是我替换后没有报错,但也读不出文件中的内容(不替换时可以读出),请问哪里出错了。(我用的是python2.5版)

作者: eeeee159963   发布时间: 2010-12-08

回复 eeeee159963

在for record in file前面是不是调用了file.readlines()?如果你已经读过一个文件对像了,那流的位置是在文件末尾,是读不到东西的。 seek到开头就行了

作者: donotblock   发布时间: 2010-12-08