簡體   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