Python - 删除文本文件中的最后一个字符

时间:2015-11-03 18:49:07

标签: python string text

我正在生成一个文件文本,如下所示,我试图压制最后一个字符","生成它之后的文件文本,但我不能...

*Nset, nset
0570, 0571, 0572, 0573, 0574, 0575, 0576, 0577, 0578, 0579, 0579
0580, 0581, 0582, 0583, 0584, 0585, 0586, 0587, 0588, 0589, 0589
0590, 0591, 

我在Stack上发现了这种代码,但它不起作用......

import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
     for line in f:
         out.write(line.split()[-1]+'\n')

----编辑以后----

生成文件文本的代码:

fichier_write.write("*Nset,")
fichier_write.write("\n")
compt = 0
for i in range(0,node_label.size):
    if Eleme_CI[i]!=0:
        fichier_write.write("%.4i, "%(Eleme_CI[i])),
        compt = compt + 1
    if compt == 10: 
        fichier_write.write("%.4i"%(Eleme_CI[i])),
        fichier_write.write("\n")
        compt = 0

fichier_write.close()  

2 个答案:

答案 0 :(得分:2)

import re
# get text into a string \Z is the end of a string in regex
with open('data') as f:
    text = f.read()

text = re.sub(r'.\Z',r'',text)

print(text)

Money amount left 39.0
*Nset, nset
0570, 0571, 0572, 0573, 0574, 0575, 0576, 0577, 0578, 0579, 0579
0580, 0581, 0582, 0583, 0584, 0585, 0586, 0587, 0588, 0589, 0589
0590, 0591

答案 1 :(得分:1)

当您生成输出时,请尝试:

for i in range(0,node_label.size):
    if compt == 10 or i == node_label.size: 
        fichier_write.write("%.4i"%(Eleme_CI[i])),
        fichier_write.write("\n")
        compt = 0
    if Eleme_CI[i]!=0:
        fichier_write.write("%.4i, "%(Eleme_CI[i])),
        compt = compt + 1

我在第二个if语句中添加了一点,然后切换了顺序。如果这是连续的第10个数字或者它是最后一个数字,请不要打印“,”。我切换了订单,以便先检查。