【发布时间】:2020-08-06 21:21:19
【问题描述】:
问题:编写您自己的代码版本,提示输入要读取的文件名和要打印的行数。
我试着喜欢这个:
import linecache
line=int(input("Line: "))
print(linecache.getline("Test.txt",line))
但不能解决最后一个问题,如果输入大于已经存在的行,所有行都将显示
【问题讨论】:
标签: python-3.x computer-science
问题:编写您自己的代码版本,提示输入要读取的文件名和要打印的行数。
我试着喜欢这个:
import linecache
line=int(input("Line: "))
print(linecache.getline("Test.txt",line))
但不能解决最后一个问题,如果输入大于已经存在的行,所有行都将显示
【问题讨论】:
标签: python-3.x computer-science
file=input('File name: ')
print(os.access(file,os.F_OK))#check whether file is available or not
no_of_lines=int(input('Lines: '))
file_length=0
with open(file,'r') as f:
file_length=len(f.readlines())
with open(file,'r') as f:
if file_length<no_of_lines:
print(f.read())
else:
for i in range(no_of_lines):
print(f.readline().rstrip('\n'))
【讨论】: