Add Character at the end of the line

Asked

Viewed 75 times

2

Greetings,

when I add a ";" to the end of the file, even if I specify that it is not to add if I am done with it, it is still added:

newf=""
with open('teste.txt','r') as f:
    for line in f:
        lastchar = line[-1]
        print(lastchar)
        if lastchar != ';':
         newf+=line.strip()+";\n"
        else:
         newf+=line.strip()
    f.close()
with open('teste.txt','w') as f:
    f.write(newf)
    f.close()

The text that is:

1;2
2;2;
3;3

Fica

1;2;
2;2;;
3;3;

How to solve?

  • I could not find error in logic, what is printing for example when putting lastchar?

  • something like: "null null 3"

3 answers

4


First, some considerations about your code:

If you’re wearing one context manager with with open(..., you don’t need to close the file with f.close(). The context manager does it for you.

I suggest that you do not overwrite the input file, mainly with data in memory. If anything goes wrong while writing the final file and the program ends with error, you lose the processed data and the original file. Save a temporary file and rename the temporary file to the original at the end of processing.

In the same line as the previous item, do not put everything in memory and then start writing to the target file. This works well for a small file, but if the file has 100GB, there is memory... Record the file line by line.

You also don’t need to open a file using a context manager, put all the result in memory and then use another context manager to open the same file (or other) to write the result. Open the two files, input and output in it context manager.

Make it work

The problem is that you are only considering the line break character afterward of if. You could remove the line break before testing if the ';' is there.

But you can also keep it that way by testing the string from the penultimate position, with the method endswith() and only remove the break in the lines where you will add the ';'. And just do the rstrip(), because the beginning of the line doesn’t matter.

Then add line break back using '\n', only on modified lines.

Would look like this:

with open('teste.txt','r') as inFile, \
     open('teste.tmp.txt', 'w') as outFile:

    for line in inFile:
        if not line.endswith(';', -2, len(line) - 1):
            line = line.rstrip() + ';\n'
        outFile.write(line)

Or, if you want to program in "job guarantee mode"... :)

with open('teste.txt','r') as inFile, open('teste.tmp.txt', 'w') as outFile: outFile.write(''.join([line.rstrip() + ';\n' if not line.endswith(';', -2, (len(line) - 1)) else line for line in inFile]))
  • 1

    A detail (which is not the focus of the question, but only to make the answer more complete): the temporary file was not renamed at the end - and to create the tmp file I suggest the use of module tempfile, you have an example here: https://answall.com/a/440054/112052

  • 1

    Sorry for the delay in answering, but it worked correctly and in a much simpler way. I started to join with not only in python but also in VB. Thank you very much for the usability tips.

0

There seems to be no error in your logic, but the fact that it is returning false always in if means that the variable lastchar is not a semicolon as you expected. Very likely this is happening because line has white spaces at the end, ie if you do lastchar = line.rstrip()[-1], should solve the problem.

0

The problem is that each end of the file line has a line break(" n"). One solution is to call the method replace of str to replace the " n" by "".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.