user5927494
user5927494

Reputation: 129

Python: Adding a column of the same value

I have a tab-delimeted file that contains 3 columns. I would like to add a new first column of just same number 1.

inputfile is

a 3 6
b 3 5
c 3 5 
d 8 4 

This is what I would like to have for my outputfile:

1 a 3 6
1 b 3 5
1 c 3 5
1 d 8 4

This is what I have so far:

#!/usr/bin/env python
import sys
import csv  
f=open('inputfile.txt', 'r+')
t=[]
for line in f.readlines():
    t.append('\n')
    t.append(1)
    f.writelines(t)

However, I am getting an error: Traceback (most recent call last): File "./py.py", line 6, in sys.stdout('inputfile.txt', 'w') TypeError: 'file' object is not callable

Upvotes: 0

Views: 114

Answers (4)

Parfait
Parfait

Reputation: 107652

Simply open both files and write to it, concatenating a 1 and tab \t to each line in a running list. Then output list to new file:

f1 = "Input.txt"
f2 = "Output.txt"

t = []
with open(f1, 'r') as txt1:
    for rline in txt1:       
        t.append("1\t" + rline)

with open(f2, 'w') as txt2:
    for i in t:
        txt2.write(i)

#1  a   3   6
#1  b   3   5
#1  c   3   5
#1  d   8   4

Alternatively, to avoid use of a list (but requires appending to file with 'a'):

with open(f1, 'r') as txt1:
    for rline in txt1:       
        rline = "1\t" + rline

        with open(f2, 'a') as txt2:
            txt2.write(rline)

And even further suggested by @JonClements that avoids the overhead of opening/closing file with each line:

with open(f1) as txt1, open(f2, 'w') as txt2:
        txt2.writelines('1\t' + line for line in txt1) 

Upvotes: 2

scope
scope

Reputation: 1997

If you do not want nothing else you can skip csv module and just prepend each line in a file, like this:

open('out.txt', 'w').writelines(["1\t" + line for line in open("in.txt")])

Upvotes: 0

mushfiq
mushfiq

Reputation: 1600

You don't need sys module for the solution:

#!/usr/bin/env python
output_file = open('output.txt', 'w')
input_file = open('input.txt', 'r+')
for line in input_file.readlines():
    line = line.split(" ")
    line.insert(1, str(1))
    line = (" ").join(line)
    output_file.write(line)

input_file.close()    
output_file.clsoe()

cat output.txt gives output:

a 1 3 6
b 1 3 5
c 1 3 5
d 1 8 4

Upvotes: 1

Aaron
Aaron

Reputation: 1016

This will give you exactly what your desired output shows:

fin = open('inputfile.txt', 'r+')
fout = open('outputfile.txt', 'w')
t=[]

for line in fin.readlines():
    t.append('1 ' + line)

fout.writelines(t)

Upvotes: 0

Related Questions