【问题标题】:Python:Reading specific line from user and show the linePython:从用户读取特定行并显示该行
【发布时间】:2020-08-06 21:21:19
【问题描述】:

问题:编写您自己的代码版本,提示输入要读取的文件名和要打印的行数。

谁能帮我用python解决这个问题?

我试着喜欢这个:

import linecache

line=int(input("Line: "))

print(linecache.getline("Test.txt",line))

但不能解决最后一个问题,如果输入大于已经存在的行,所有行都将显示

【问题讨论】:

    标签: python-3.x computer-science


    【解决方案1】:
    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'))
    

    【讨论】:

    • 我使用 open() 两次的原因,因为一旦文件操作完成,连接就会自动关闭
    • @Shihab Omar 我认为你的疑问已经得到纠正
    猜你喜欢
    • 2013-04-23
    • 2016-05-25
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多