from sys import argv
script, filename = argv
print "Is %r the file you wish to open?" % filename
print "If you do not wish to continue type CTRL-C (^C)."
print "If you do wish to continue, please hit RETURN."
raw_input("Are you sure?")
print "Opening %r please wait... " % filename
target = open(filename, 'r')
print "Thank you for you request."
print "The file contains the lyrics to a certain song, can you guess it?"
target.read("line 1: ")
target.read("\n")
target.read("line 2: ")
target.read("\n")
target.read("line 3: ")
target.read("\n")
target.read("line 4: ")
target.read("\n")
song = raw_input("Go on, take a guess!")
print "%r? Good Guess!" % song
print "Goodbye!"
target.close()
答案 0 :(得分:2)
将代码的中间块更改为:
print "Opening %r please wait... " % filename
print "Thank you for you request."
print "The file contains the lyrics to a certain song, can you guess it?"
with open(filename, 'r') as target:
for lineNum in range(4):
print target.readline()
如果您打算在该行之前打印行号,您可以执行类似
的操作with open(filename, 'r') as target:
for lineNum in range(1,5):
print 'line {}: '.format(lineNum) + target.readline()
答案 1 :(得分:0)
使用target.readline()
"第1行:"而且是垃圾。默认情况下也会读取新行,您无需阅读它!
答案 2 :(得分:0)
文档说open
会返回file object。文件对象使用read
方法,使用可选的size
参数来读取一定量的字节:
file.read([size])
从文件中读取最多size
个字节(如果是,则更少) 读取在获得size
个字节之前命中EOF。如果size
参数是 否定或省略,读取所有数据,直到达到EOF
。字节是 作为字符串对象返回。EOF
为空时返回空字符串 遇到了。 (对于某些文件,比如ttys,它是有道理的 在EOF
被击中后继续阅读。)请注意,此方法可能会 为了这个目的,不止一次地调用底层C函数fread()
获取尽可能接近size
个字节。还要注意,在 非阻塞模式,甚至可以返回比请求的数据少的数据 如果没有给出size
参数。
您正在通过size="line 1: "
。