如何删除输出文件的最后一行?

发布于 2025-01-11 09:00:30 字数 964 浏览 0 评论 0原文

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

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()

输出文件 这张图中的第 13 行就是我需要的

Been trying to write my PYTHON code but it will always output the file with a blank line at the end. Is there a way to mod my code so it doesn't print out the last blank line.

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
Line 13 in this picture is what I need gone

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愛上了 2025-01-18 09:00:30

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

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()

Put in a check so that the new line is not added for the last element of the list:

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()
小耗子 2025-01-18 09:00:30

问题出在这里:

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:,这样您就可以始终关闭文件,并且异常不会使文件挂起

The issue is here:

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

The \n adds a new line.

The way to fix this is to rewrite it slightly:

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))

Just btw, you should actually not use file_out = open() and file_out.close() but with open() as file_out:, this way you always close the file and an exception won't leave the file hanging

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文