user3601754
user3601754

Reputation: 3862

Python - Remove the last character in a text file

I m generating a file text as you can see below and i m trying to suppress the last character "," of this file text after generating it but i cant...

*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, 

I have found on Stack this kind of code, but, it doesnt work...

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

----EDIT LATER----

My code to generate the file text :

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

Upvotes: 1

Views: 6483

Answers (2)

Programmingjoe
Programmingjoe

Reputation: 2249

When you are generating the output try this:

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

I added a bit to the second if statement and I switched the order. If this is the 10th number in a row or if it is the last number overall, don't print the ",". I switched the order so that is checked first.

Upvotes: 1

LetzerWille
LetzerWille

Reputation: 5658

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

Upvotes: 2

Related Questions