我正在尝试插入文件,并且在line = infile.redline()
def main():
# Declare variables
line = ''
counter = 0
# Prompt for file name
fileName = input('Enter the name of the file: ')
# Open the specified file for reading
infile = open('test.txt', 'r')
# Priming read
line = infile.redline()
counter = 1
# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '\n'
line = line.rtrip('\n')
print(line)
1ine = infile.readline()
# Update counter when line is read
counter +=1
# Close file
infile.close()
# Call the main function.
main()
答案 0 :(得分:1)
rtrip
应为rstrip
。 redline
应为readline
。 infile.close()
应缩进,main()
不应该缩进。
然而,最严重的问题是:
1ine = infile.readline()
第一个角色是一个,而不是L。
答案 1 :(得分:1)
了解标准库可以让您的生活更轻松!
from itertools import islice
def main():
fname = input('Enter the name of the file: ')
with open(fname) as inf:
for line in islice(inf, 5): # get the first 5 lines
print(line.rstrip())
if __name__=="__main__":
main()
答案 2 :(得分:0)
不是redline
而是readline
:
line = infile.redline()