Skip to content
Advertisement

Append Text (Single Letter) to the end of each line in a text file

Below is an example of the text file I am working with:

437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,54435A000,510,Social Studies (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,100,05/29/2014,
437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,53235A000,500,Science (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,100,05/29/2014,
437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,58035A000,560,Physical Education (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,1,05/29/2014,

I am trying to add simply the letter ‘S’ to the end of every other line. So, above, there 3 total records. Right after 05/29/2014, I want to insert the S. So a every record would look like:

437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,54435A000,510,Social Studies (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,100,05/29/2014,S

I realize this would be Oh so simple converting to CSV and working with excel, but I’m getting all sorts of formatting issues on the transfer back to txt. Wanted to take a crack at it with python. I’m trying to use append, from what I understand, write will overwrite my existing file:

myFile = open("myFile.txt", "a")
    for line in myFile:
        myFile.write('S')

I don’t use python often, I’m wondering how I can index it so it starts with line 2, and appends the very end of the line after the comma, like I noted above.

Advertisement

Answer

You’ll need to read the file line by line and then output line by line again. This is much simpler than using CSV or even spread sheet processing software which truly scares me.

with open('input.txt', 'r') as istr:
    with open('output.txt', 'w') as ostr:
        for i, line in enumerate(istr):
            # Get rid of the trailing newline (if any).
            line = line.rstrip('n')
            if i % 2 == 0:
                line += 'S'
            print(line, file=ostr)

If you are still using Python 2, use

ostr.write(line + 'n')

instead of the print.

Update: If you want to append to every (as opposed to every other) line, simply use:

with open('input.txt', 'r') as istr:
    with open('output.txt', 'w') as ostr:
        for line in istr:
            line = line.rstrip('n') + 'S'
            print(line, file=ostr)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement