繁体   English   中英

如何阅读整行?

[英]How to read the whole line?

我尝试向用户询问行号并显示它,但它一直显示第一个字母而不是行。

而且我不知道如何循环 IoError 和 IndexError。

谢谢

这是我的代码

def file_content(file_name):
    user_file = open(file_name, 'r')
    content = user_file.read()
    user_file.close()
    return content
def main():
    file_name = input('Enter the name of the file: ')



    try:
       content = file_content(file_name)
    

    except IOError:
       print ('File can not be fount. Program wil exit.')
       exit()

    try:
    
       line_number = int(input('Enter a line number: '))

    except ValueError:
        print ('You need to enter an integer for the line number. Try again.')

    except IndexError:
        print ('that is not a valid line number. Try again.')

    
    print ('The line you requested:')
    print (content[line_number-1])

 main()

content只是您使用read()时文件的内容 - 因此打印content[-1]打印内容中的最后一个内容,即最后一个字符。

如果您希望内容为行,则 a) 打开文件 'rt' 并 b) 使用readlines() ) 读取它,您可能需要注意其中包括以该行结尾的行:

def file_content(file_name):
    user_file = open(file_name, 'rt')
    content = user_file.readlines()
    user_file.close()
    return content

现在content[-1]是最后一行。

barny 有一个很好的答案,但使用 readlines() 并不是最佳实践 您可能会考虑将您的file_content function 替换为不会立即将整个文件加载到 memory 中的内容,如下所示:

def file_content(filename):
  result = []
  with open(filename, 'r') as input_file:
    result = list(input_file)
  return result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM