'Want to append a column in a file without using the Pandas

I have a file say, outfile.txt which looks like below:

1,2,3,4,0,0.95
1,2,4,4,0,0.81
5,6,3,1,0,0.89
7,6,8,8,0,0.77
6,6,4,9,0,0.88
9,9,9,1,0,0.66
4,3,6,9,0,0.85
1,2,6,7,0,0.61

Now I want to append one extra 1 to each row. So the desired output file looks like:

1,2,3,4,0,0.95,1
1,2,4,4,0,0.81,1
5,6,3,1,0,0.89,1
7,6,8,8,0,0.77,1
6,6,4,9,0,0.88,1
9,9,9,1,0,0.66,1
4,3,6,9,0,0.85,1
1,2,6,7,0,0.61,1

How can I do it? Whenever I am googling it to find a solution, I am seeing everywhere this kind of solution is provided using Pandas, But I don't want to use that.



Solution 1:[1]

Just, iterate through the file line by line and add ,1 at the end of each line:

with open('outfile.txt', 'r') as input:
    with open('outfile_final.txt', 'w') as output:
        for line in input:
            line = line.rstrip('\n') + ',1'
            print(line, file=output)

Solution 2:[2]

Since your file is in csv format, csv module can help you. If you iterate over the reader object, it gives you a list of the items in each line in the file, then simply .append() what you want.

import csv

with open("outfile.txt") as f:
    reader = csv.reader(f)
    for line in reader:
        line.append("1")
        print(",".join(line))

If you have a column like column you can zip it with the reader object and append the corresponding element in the loop:

import csv

column = range(10)

with open("outfile.txt") as f:
    reader = csv.reader(f)
    for line, n in zip(reader, map(str, column)):
        line.append(n)
        print(",".join(line))

I printed, you can write it to a new file.

Solution 3:[3]

You can read and write files line by line with the csv module. A reader object will iterate the rows of the input file and writer.writerows will consume that iterator. You just need a bit of extra code to add the 1. Using a list generator, this example adds the extra column.

import csv
import os

filename = "outfile.txt"
tmp = filename + ".tmp"
    
with open(filename, newline="") as infile, open(tmp, "w", newline="") as outfile:
    csv.writer(outfile).writerows(row + [1] for row in csv.reader(infile))
os.rename(tmp, filename)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3