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]))
I could not find error in logic, what is printing for example when putting lastchar?
– renatomt
something like: "null null 3"
– Arcyde