我的问题:程序从txt文件中读取前n行,将n作为用户输入。我试过了
f1=open('sampletest.txt','r')
n=int(input("Enter number of lines to be read from the txt file:"))
line=f1.readlines(n)
print(line)
f1.close()
我命名为sampletest的txtfile内容如下:
汤姆和杰里是卡通人物。
汤姆是猫。
杰里是一只老鼠。
他们有一个共同的朋友,斯派克。
狼是狗。
通过执行python代码得到的输出:输入要从txt文件读取的行数:3 ['Tom和Jerry是卡通人物。\ n']
我该如何更正我的代码?我是编码新手。请帮忙。提前致谢。
f1=open('sampletest.txt','r')
n=int(input("Enter number of lines to be read from the txt file:"))
line = ''.join(f1.readline() for _ in range(n))
print(line)
f1.close()
您的代码不起作用,因为readlines接受hint
参数而不是要读取的行数
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句