如何删除输出文件的最后一行?
一直在尝试编写我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
进行检查,以便不会为列表的最后一个元素添加新行:
Put in a check so that the new line is not added for the last element of the list:
问题出在这里:
\n
添加了一个新行。解决这个问题的方法是稍微重写它:
顺便说一句,你实际上不应该使用
file_out = open()
和file_out.close()
而是使用with open () as file_out:
,这样您就可以始终关闭文件,并且异常不会使文件挂起The issue is here:
The
\n
adds a new line.The way to fix this is to rewrite it slightly:
Just btw, you should actually not use
file_out = open()
andfile_out.close()
butwith open() as file_out:
, this way you always close the file and an exception won't leave the file hanging