简体   繁体   English

读取 python 上空文件的最后一行

[英]Reading the last line of an empty file on python

I have this function on my code that is supposed to read a files last line, and if there is no file create one.我的代码中有这个 function,它应该在最后一行读取文件,如果没有文件,则创建一个。 My issue is when it creates the files and tries to read the last line it comes up as an error.我的问题是当它创建文件并尝试读取最后一行时出现错误。

with open(HIGH_SCORES_FILE_PATH, "w+") as file:
        last_line = file.readlines()[-1]
        if last_line == '\n':
            with open(HIGH_SCORES_FILE_PATH, 'a') as file:
                file.write('Jogo:')
                file.write('\n')
                file.write(str(0))
                file.write('\n') 

I have tried multiple ways of reading the last line but all of the ones I've tried ends in an error.我尝试了多种阅读最后一行的方法,但我尝试过的所有方法都以错误告终。

Opening a file in "w+" erases any content in the file.在“w+”中打开文件会删除文件中的所有内容。 readlines() returns an empty list and trying to get value results in an IndexError . readlines()返回一个空列表并尝试获取值导致IndexError You can test for a file's existence with os.path.exists or os.path.isfile , or you could use an exception handler to deal with that case.您可以使用os.path.existsos.path.isfile测试文件是否存在,或者您可以使用异常处理程序来处理这种情况。

Start with last_line set to a sentinel value.last_line开始设置为标记值。 If the open fails, or if no lines are read, last_line will not be updated and you can base file creation on that.如果打开失败,或者没有读取任何行,则不会更新last_line ,您可以基于它创建文件。

last_line = None
try:
    with open(HIGH_SCORES_FILE_PATH) as file:
        for last_line in file:
            pass 
except OSError:
    pass

if last_line is None:
    with open(HIGH_SCORES_FILE_PATH, "w") as file:
        file.write('Jogo:\n0\n')
    last_line = '0\n'

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

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