0

I am very new to Python and I am trying to do a very simple merge of every two lines in a csv file. Basically I want it like this:

Input:

[H1],1,2,3,4
[H2],5,6,7,8
[H1],a,b,c,d
[H2],e,f,g,h

Output:

[H1],1,2,3,4,[H2],5,6,7,8
[H1],a,b,c,d,[H2],e,f,g,h

This is a brief example, but the csv file has up to 167 columns with the two lines combined. This is what I have:

import csv
f = open("sample.csv",'rU').read().split("\n")
reader = csv.reader(f)
for row in reader:
    if row[0].startswith("[H1]"): 
        i=[]
        while i<167: n = row.append([",".join(row[i]+row[i+1])])
        print n

However when I run it I get the following error:

    print n
NameError: name 'n' is not defined

Any help is appreciated, thanks.

3
  • row.append does not return anything. What is n supposed to be? If i = [], what is while i < 167 supposed to mean? Commented Jul 21, 2014 at 9:27
  • You are comparing a list (i) with a number (167). So that while loop either never runs → no defining of n, or will be an endless loop. Commented Jul 21, 2014 at 9:29
  • I am trying to save the concatenated row into 'n'. For i=[], that was a mistake, I just want it to loop through 167 times. Commented Jul 21, 2014 at 9:32

4 Answers 4

1

Input i.csv:

1,2,3
foo,bar,baz
4,5,6
qux,quux.quuux

Python codce:

with open("i.csv") as f:
    reader = csv.reader(f)
    i = 0
    for row in reader:
        if i % 2 == 0:
            newRow = row
        else:
            newRow = newRow + row
            print(newRow)
        i = i + 1

Output:

['1', '2', '3', 'foo', 'bar', 'baz']
['4', '5', '6', 'qux', 'quux', 'quuux']
Sign up to request clarification or add additional context in comments.

1 Comment

Not binding the open file to a name makes it impossible to close it after it's not needed anymore.
1
import csv

f = open("sample.csv",'rU').read().split("\n")
reader = csv.reader(f)

i = 0

for row in reader:
    if i % 2 == 0:
        line = row
    else:
        line = line + row
        print ", ".join(line)

    i += 1

1 Comment

First line number is even, second odd (i). You need even number of lines in the CSV file to make it work for all pairs.
0

Writing while i<167: n = row.append([",".join(row[i]+row[i+1])]) is like writing:

while i<167:
    n = row.append([",".join(row[i]+row[i+1])])

So the scope of n is the loop block. Your print n is out of that scope thus raising NameError.

You could add n = None right before the while:

n = None
while i<167: n = row.append([",".join(row[i]+row[i+1])])
print n

Or move print n into the loop block:

while i<167:
    n = row.append([",".join(row[i]+row[i+1])])
    print n

Note that any of these changes will avoid your program interruption by the out of scope error but you will print a lot of lines containing None because append returns None: https://docs.python.org/2/tutorial/datastructures.html

5 Comments

What does row.append return?
@Tichodroma It returns None, so it doesn't make sense.
@Tichodroma It returns None but that is not the origin of the exception. Just another problem with the OP code.
@BlackJack Right, that's why I am asking.
@PabloFranciscoPérezHidalgo So your answer removes the scope problem but still the OP doesn't have a working solution. Of course, that's because we don't know waht the OP is trying to do.
0

Here is a way to combine the line pairs:

import csv
from itertools import izip


def main():
    with open('sample.csv', 'rb') as input_file:
        reader = csv.reader(input_file)
        for even_row, odd_row in izip(reader, reader):
            combined_row = even_row + odd_row
            print combined_row


if __name__ == '__main__':
    main()

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.