1

I want to add a new column to the beginning of a csv file, and I thought iterating through each row and just adding together a list containing my new column's content and the old list would work, and it does, but it only works inside the loop. Why is it doing that?

file:

column1 column2 column3
x1      y1      z1
x2      y2      z2

intended output:

0 column1 column2 column3
0 x1      y1      z1
0 x2      y2      z2

code:

import csv

x = open('C:/Documents and Settings/admin/Desktop/sample.csv')
y = csv.reader(x)
z = []
for row in y:
    z.append(row)
for n in z:
    n = ['0'] + n
    print(n)

for m in z:
    print(m)

what I get:

[0, column1, column2, column2]
[0, x1, y1, z1]
[0, x2, y2, z2]
[column1, column2, column2]
[x1, y1, z1]
[x2, y2, z2]

The zeros basically disappear outside that loop. Why?

Thanks!

Anj
  • 115
  • 2
  • 10
  • Because of you do not change elements of `z`. You have to write like: `for i,n in enumerate(z): z[i] = ['0'] + n` – Serenity Apr 11 '17 at 11:45
  • Maybe this help: [Do Python for loops work by reference?](http://stackoverflow.com/questions/14814771/do-python-for-loops-work-by-reference) – Fogmoon Apr 11 '17 at 11:48

2 Answers2

1

The particular "glitch" you're seeing is because of a result of scoping. Even though your first loop is setting n as ['0'] + n, it only happens within the scope of that loop, without ever changing z.

What you could do is create a new list and appending the new n to that list:

new_list = []
for n in z:
    n = ['0'] + n
    new_list.append(n)

for m in new_list:
    print(m)
Scratch'N'Purr
  • 9,959
  • 2
  • 35
  • 51
0

You can achieve this if you change z when you change your row

import csv

x = open('C:/Documents and Settings/admin/Desktop/sample.csv')
y = csv.reader(x)
z = []
for row in y:
    z.append(['0'] + row)
print(z)

for m in z:
    print(m)
CodeCupboard
  • 1,507
  • 3
  • 17
  • 26