0

I have two example csv files to make it easier, where csvexample.csv looks like this:

ID Text
1 'goodmorning'
2 'goodafternoon'
3 'goodevening'

The csvexample1.csv file looks like this:

Day Month
17 'Feb'
18 'Mar'
19 'May'

I want the first column of the first file and the second column of the second file to be added to one singular list. So far I have the following code:

import csv
from collections import defaultdict
columns = defaultdict(list)


with open('csvexample.csv') as f, open('csvexample1.csv') as a:
    reader=csv.reader(f)
    reader1=csv.reader(a)
    next(reader)
    next(reader1)
    for row in reader:
        for(i,v) in enumerate(row):
            columns[i].append(v)
    print (columns[0])
    for row in reader1:
        for (b,c) in enumerate(row):
            columns[b].append(c)
    print (columns[1])

This gives me the following outcome:
['1','2','3']
['Goodmorning', 'Goodafternoon', 'Goodevening ', 'Feb', 'Mar', 'May']

I'm quite new to python and I kind of do understand why I'm getting this result, but I am not sure how to fix it. I want the outcome to be:
['1', '2', '3', 'Feb', 'Mar', 'May'] but nothing I try seems to be working.

1 Answer 1

1

Ex:

import csv
columns = defaultdict(list)

res = []
with open(filename) as f, open(filename2) as a:
    reader=csv.reader(f, delimiter=' ')
    reader1=csv.reader(a, delimiter=' ')
    next(reader)
    next(reader1)
    for row in zip(reader, reader1):
        res.extend([row[0][0], row[1][1].replace("'", "")])
print(res)

Output:

['1', 'Feb', '2', 'Mar', '3', 'May']
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! this code gives me an error though: Traceback (most recent call last): File "new.py", line 12, in <module> res.extend([row[0][0], row[1][1].replace("'", "")]) IndexError: list index out of range
try with out delimiter=' '

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.