CarterZhang 发表于 2020-11-22 10:55:09

打印文件的前n行

题目要求:当用户输入文件名和行数(N)后,将该文件的前N行内容打印到屏幕上。


def print_lines(file,n):
    f1 = open(file,'r')
    for i in range(int(n)):
      print(f1.readline,end = ' ')
      
    f1.close

file = input('which file do you want to print:')
n = input('how many rows do you want to print:')
print_lines(file,n)

以上程序,我的运行结果如下,请大佬问题出在哪?该如何改进?

<built-in method readline of _io.TextIOWrapper object at 0x000001A162DA81E0> <built-in method readline of _io.TextIOWrapper object at 0x000001A162DA81E0> <built-in method readline of _io.TextIOWrapper object at 0x000001A162DA81E0>

逃兵 发表于 2020-11-22 11:05:08

f1.readline 忘记了加括号
close 忘了加括号
def print_lines(file,n):
    f1 = open(file,'r')
    for i in range(int(n)):
      print(f1.readline(),end = '')
      
    f1.close()

file = input('which file do you want to print:')
n = input('how many rows do you want to print:')
print_lines(file,n)

CarterZhang 发表于 2020-11-22 11:06:38

逃兵 发表于 2020-11-22 11:05
f1.readline 忘记了加括号
close 忘了加括号

谢谢大佬,低级错误,麻烦了!
页: [1]
查看完整版本: 打印文件的前n行