如果这是糟糕的代码,我提前致歉。这是我完全无助地尝试做的第一件事。我试图让它从文件中读取前4行。
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()
将代码的中间块更改为:
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected]l.com 删除。
我来说两句