繁体   English   中英

如何删除我的 output 文件的最后一行?

[英]How to delete the last line of my output file?

一直在尝试编写我的 PYTHON 代码,但它总是 output 文件末尾有一个空行。 有没有办法修改我的代码,这样它就不会打印出最后一个空行。

def write_concordance(self, filename):
        """ Write the concordance entries to the output file(filename)
        See sample output files for format."""
        try:
            file_out = open(filename, "w")
        except FileNotFoundError:
            raise FileNotFoundError("File Not Found")
        word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
        word_lst.sort() #orders it
        for i in word_lst:
            ln_num = self.concordance_table.get_value(i) #line number list
            ln_str = "" #string that will be written to file

            for c in ln_num:
                ln_str += " " + str(c) #loads line numbers as a string
            file_out.write(i + ":" + ln_str + "\n")
        file_out.close()

这张图片中的Output_file第 13 行是我需要的

检查以便不为列表的最后一个元素添加新行:

def write_concordance(self, filename):
    """ Write the concordance entries to the output file(filename)
    See sample output files for format."""
    try:
        file_out = open(filename, "w")
    except FileNotFoundError:
        raise FileNotFoundError("File Not Found")
    word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
    word_lst.sort() #orders it
    for i in word_lst:
        ln_num = self.concordance_table.get_value(i) #line number list
        ln_str = "" #string that will be written to file

        for c in ln_num:
            ln_str += " " + str(c) #loads line numbers as a string

        file_out.write(i + ":" + ln_str)

        if i != word_lst[-1]:
            file_out.write("\n")
    file_out.close()

问题在这里:

file_out.write(i + ":" + ln_str + "\n")

\n添加一个新行。

解决这个问题的方法是稍微重写它:

ln_strs = []
for i in word_lst:
   ln_num = self.concordance_table.get_value(i) #line number list
   ln_str = " ".join(ln_num) #string that will be written to file
   ln_strs.append(f"{i} : {ln_str}")
file_out.write('\n'.join(ln_strs))

顺便说一句,你实际上不应该使用file_out = open()file_out.close()而是with open() as file_out: ,这样你总是关闭文件并且异常不会让文件挂起

暂无
暂无

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

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