0

I have two CSV files that have the same number of columns.

I want to insert file 1 as the first column into file2 and generate the output as a new CSV file.

Input Files:

file1:
offset;
1;
2;
3;
.
.
.
n
file2:
status;value
ok;12
nok;13
ok;14
.
.
.
ok;n

Needed Output File:

offset;status;value
1;ok;12
2;nok;13
3;ok;14
.;.;
.;.;
.;.;
n;ok;n

2 Answers 2

1

I will just start with the code sample (I based test1 and test2.csv directly from your provided data in your post):

## Read first csv into list
f = open("test1.csv", "r")
csv1 = f.readlines()
f.close()

## Read second csv into list
f = open("test2.csv", "r")
csv2 = f.readlines()
f.close()

## Create new csv header
header = csv1[0].replace("\n", "") + "," + csv2[0].replace("\n", "")

## Create data list and append lines from csv1 and csv2
data = []
for x in range(1, len(csv1)):
    data.append(csv1[x].replace("\n", "") + "," + csv2[x].replace("\n", "") + "\n")

## Print new header and data to a new csv file
f = open("test3.csv", "w")
f.write(header + "\n")
f.writelines(data)

The comments for this are pretty straight forward and let you know what each code block accomplishes.

Doing something like this works under the assumption there is no key to associate the data from one file to the other (like in a database you have an ID to associate between tables).

You could also use the builtin csv library and break this out into functions, etc, etc, but for something this simple I find it easier to just write it out as I did.

Here is the output:

offset,status,value
1,ok,12
2,nok,13
3,ok,14
Sign up to request clarification or add additional context in comments.

Comments

1

You could iterate over both files simultaneously using this:

file1 = open("test1.csv", "r")
file2 = open("test2.csv", "r")
file3 = open("test3.csv", "w")
for line1, line2 in zip(file1, file2):
    file3.write(line1+line2+"\n")
file1.close()
file2.close()
file3.close()

This assumes that both files have the same number of lines. If this weren't true this aproach would only concatenate lines up until the shorter file end. i.e: if file1 has 10 lines and file2 has 15 lines the output file would ignore last 5 lines from file2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.