List Manipulation

R

Roman

I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
p[:0].append(str(col))
cnt = cnt + 1

print p

when I change it to the following, I get rows back

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
print col
cnt = cnt + 1

print p


Thanks in advance
 
M

Mike Kent

Roman said:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
p[:0].append(str(col))
cnt = cnt + 1

print p

I'm having trouble deciding what you *intend* this program to do. It
looks like you want to take the first 7 lines of the input file, and
append all the data elements in those lines into one long list. If
that's what you want to do, then you are almost there, although you
could have written it better. If that's NOT what you want to do...
well, there are tutorials.

The problem with this code is in the line 'p[:0].append(str(col)).
Given a list p, p[:0] will give you the part of p *prior* to element 0.
Since there is never anything in a list prior to element 0, you will
always get an empty list back.

I assume this is not what you intended. But just *what* do you intend?
I sure can't say.
 
I

Iain King

Roman said:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
p[:0].append(str(col))

What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert


Iain
 
L

Laszlo Nagy

Roman írta:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
p[:0].append(str(col))
You are appending to a slice. In that case, p[:0] creates a new list
object. You are not appending to p but to a new object (created from a
slice).
If you need to insert an item at the begining of a list, use the insert
method instead.
>>> l = [2,3,4]
>>> l.insert(1,0)
>>> l
[2, 0, 3, 4]


Best,

Laszlo
 
S

Steven D'Aprano

I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

What do you mean? Does it print None?
cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break

That's a very unPythonic way of doing the job. The usual way of doing
this would be something like this:

for line in reader[:7]:
# no need for the "if cnt > 6: break" clause now

for col in line:
p[:0].append(str(col))

p[:0] creates a new list, which has a string appended to it, and is then
thrown away. What are you trying to do?

If you are trying to insert the new entry at the beginning of the list,
you probably want this:

p.insert(0, str(col))
 
R

Roman

Thanks for your help

My intention is to create matrix based on parsed csv file. So, I would
like to have a list of columns (which are also lists).

I have made the following changes and it still doesn't work.


cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1

print p

Iain said:
Roman said:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
p[:0].append(str(col))

What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert


Iain
 
S

Sibylle Koczian

Roman said:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
p[:0].append(str(col))

This is wrong. I'm not absolutely certain _what_ it does, but it doesn't
append anything to list p. p[:0] is an empty copy of p, you are
appending to this empty copy, not to p. What's wrong with
p.append(str(col))?
when I change it to the following, I get rows back

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
for col in line:
print col
cnt = cnt + 1

print p

Here you print every single cell, but p doesn't change.

HTH
Koczian
 
M

Mike Kent

Roman said:
Thanks for your help

My intention is to create matrix based on parsed csv file. So, I would
like to have a list of columns (which are also lists).

I have made the following changes and it still doesn't work.


cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1

print p

p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Try doing:

p[j] = p[j].append(col)

However, this will still result in inefficient code. Since every line
you read in via the csv reader is already a list, try this (untested)
instead:

reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
p = [ line for line in reader[:7] ]
 
D

Diez B. Roggisch

p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Not correct.

p = [[]]
p[0].append(1)
print p

yields

[[1]]

p[0] _gives_ you a reference to an object. If it is mutable (list are) and
append mutates it (it does), the code is perfectly alright.

I don't know what is "not working" for the OP, but actually his code works
if one replaces the csv-reading with a generated list:

cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = [["column_%i" % c for c in xrange(5)] for l in xrange(7)]
for line in reader:
if cnt > 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1
print p


You are right of course that it is the most unpythonic way imaginabe to do
it. But it works.

Diez
 
R

Roman

Nothing got printed.

Could you tell me what would be pythonic version of what I am trying to
do?

p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Not correct.

p = [[]]
p[0].append(1)
print p

yields

[[1]]

p[0] _gives_ you a reference to an object. If it is mutable (list are) and
append mutates it (it does), the code is perfectly alright.

I don't know what is "not working" for the OP, but actually his code works
if one replaces the csv-reading with a generated list:

cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = [["column_%i" % c for c in xrange(5)] for l in xrange(7)]
for line in reader:
if cnt > 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1
print p


You are right of course that it is the most unpythonic way imaginabe to do
it. But it works.

Diez
 
B

Bruno Desthuilliers

Roman wrote:
(please dont top-post - corrected)
(snip)
What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert


Iain


Thanks for your help

My intention is to create matrix based on parsed csv file. So, I
would like to have a list of columns (which are also lists).

csv = [
['L0C0', 'L0C1', 'L0C2'],
['L1C0', 'L1C1', 'L1C2'],
['L2C0', 'L2C1', 'L2C2'],
]

matrix = [[[] for l in range(len(csv))] for c in range(len(csv[0]))]

for numline, line in enumerate(csv):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

assert matrix == [
['L0C0', 'L1C0', 'L2C0'],
['L0C1', 'L1C1', 'L2C1'],
['L0C2', 'L1C2', 'L2C2']
]

NB : There are probably more elegant solutions.
I have made the following changes and it still doesn't work.

"doesn't work" is the worst possible description of a problem...

(snip)
 
R

Roman

I am getting

TypeError: unsubscriptable object

when specifying

for line in reader[:7]:

I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

What do you mean? Does it print None?
cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break

That's a very unPythonic way of doing the job. The usual way of doing
this would be something like this:

for line in reader[:7]:
# no need for the "if cnt > 6: break" clause now

for col in line:
p[:0].append(str(col))

p[:0] creates a new list, which has a string appended to it, and is then
thrown away. What are you trying to do?

If you are trying to insert the new entry at the beginning of the list,
you probably want this:

p.insert(0, str(col))
 
B

Bruno Desthuilliers

Roman wrote:
(please dont top-post - corrected)
On Tue, 04 Jul 2006 07:01:55 -0700, Roman wrote:

(snip)
cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break

That's a very unPythonic way of doing the job. The usual way of doing
this would be something like this:

for line in reader[:7]:
# no need for the "if cnt > 6: break" clause now
I am getting

TypeError: unsubscriptable object

when specifying

for line in reader[:7]:

Should have been :

for line in list(reader)[:7]:
# code here
 
R

Roman

Thanks for spending so much time with me. I had since made the
following change.

matrix = [[[] for l in range(len(list(reader)[:10]))] for c in
range(len(list(reader)[7]))]
for numline, line in enumerate(reader):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

print matrix

I don't get mistakes anymore. However, still nothing gets printed
Bruno said:
Roman wrote:
(please dont top-post - corrected)
Iain said:
Roman wrote:

I would appreciate it if somebody could tell me where I went wrong in
the following snipet:
(snip)
What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert


Iain


Thanks for your help

My intention is to create matrix based on parsed csv file. So, I
would like to have a list of columns (which are also lists).

csv = [
['L0C0', 'L0C1', 'L0C2'],
['L1C0', 'L1C1', 'L1C2'],
['L2C0', 'L2C1', 'L2C2'],
]

matrix = [[[] for l in range(len(csv))] for c in range(len(csv[0]))]

for numline, line in enumerate(csv):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

assert matrix == [
['L0C0', 'L1C0', 'L2C0'],
['L0C1', 'L1C1', 'L2C1'],
['L0C2', 'L1C2', 'L2C2']
]

NB : There are probably more elegant solutions.
I have made the following changes and it still doesn't work.

"doesn't work" is the worst possible description of a problem...

(snip)
 
D

Dennis Lee Bieber

I would appreciate it if somebody could tell me where I went wrong in
the following snipet:
It would help if you gave a sample of the input data (three lines
worth, say) AND an example of what the final output should be from those
three lines.
for col in line:
p[:0].append(str(col))

As has been pointed out, as soon as you used the [:0], you created a
local/temporary EMPTY slice of the original P, and you are appending one
column's value to this temporary, which is then thrown away.
import csv

-=-=-=-=-=-=-=- PROGRAM
p = []

fin = open("firearms.csv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter=",")

for line in [reader.next() for i in range(7)]:
p.append(line)

fin.close()
print p
-=-=-=-=-=-=-=- OUTPUT
[['Category', 'Model', 'Caliber', 'Serial #', 'Description',
'Accessories'], ['Air', 'Daisy 717 Pistol', '.177 pellet', '', '', ''],
['Air', 'Daisy/NRA PowerLine 953 Rifle', '.177 pellet', 'n/a',
'Micrometer Peep, "Globe" front (missing alternate inserts', 'Shooting
sling'], ['Air', 'RWS Diana Model 54 "Air King" Rifle', '.22 pellet',
'4022395', 'Hunting grade - >900fps', '2-7x BSA AOL scope'], ['Air',
'Gamo/NRA', '0.177', '', 'Hunting grade - ~1000fps; NRA markings on
barrel, stock', '4x (BSA?) AOL scope, NRA badge'], ['Air',
'Walther/Crossman CP99 Pistol', '.177 pellet', '', 'CO2, repeater
(currently magazine jams trigger/safety)', ''], ['Percussion', '? New
Orleans Ace boot-pistol', '.36 lead', '', '', '']]
-=-=-=-=-=-=-=- INPUT (just first seven lines)
Category,Model,Caliber,Serial #,Description,Accessories
Air,Daisy 717 Pistol,.177 pellet,,,
Air,Daisy/NRA PowerLine 953 Rifle,.177 pellet,n/a,"Micrometer Peep,
""Globe"" front (missing alternate inserts",Shooting sling
Air,"RWS Diana Model 54 ""Air King"" Rifle",.22 pellet,4022395,Hunting
grade - >900fps,2-7x BSA AOL scope
Air,Gamo/NRA,0.177,,"Hunting grade - ~1000fps; NRA markings on barrel,
stock","4x (BSA?) AOL scope, NRA badge"
Air,Walther/Crossman CP99 Pistol,.177 pellet,,"CO2, repeater (currently
magazine jams trigger/safety)",
Percussion,? New Orleans Ace boot-pistol,.36 lead,,,



But your explanations are unclear... Maybe you wanted the first
sublist to be all the first column, etc.

-=-=-=-=-=-=-=- PROGRAM
import csv

p = None

fin = open("firearms.csv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter=",")

for line in [reader.next() for i in range(7)]:
if not p:
p = [[] for j in range(len(line))]
for c in range(len(line)):
p[c].append(line[c])

fin.close()
print p
-=-=-=-=-=-=-=- OUTPUT (same input)
[['Category', 'Air', 'Air', 'Air', 'Air', 'Air', 'Percussion'],
['Model', 'Daisy 717 Pistol', 'Daisy/NRA PowerLine 953 Rifle', 'RWS
Diana Model 54 "Air King" Rifle', 'Gamo/NRA', 'Walther/Crossman CP99
Pistol', '? New Orleans Ace boot-pistol'], ['Caliber', '.177 pellet',
'.177 pellet', '.22 pellet', '0.177', '.177 pellet', '.36 lead'],
['Serial #', '', 'n/a', '4022395', '', '', ''], ['Description', '',
'Micrometer Peep, "Globe" front (missing alternate inserts', 'Hunting
grade - >900fps', 'Hunting grade - ~1000fps; NRA markings on barrel,
stock', 'CO2, repeater (currently magazine jams trigger/safety)', ''],
['Accessories', '', 'Shooting sling', '2-7x BSA AOL scope', '4x (BSA?)
AOL scope, NRA badge', '', '']]
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
D

Dennis Lee Bieber

Thanks for spending so much time with me. I had since made the
following change.

matrix = [[[] for l in range(len(list(reader)[:10]))] for c in
range(len(list(reader)[7]))]

Allowing for line wrap...

matrix = [ <something> for c in range(len(list(reader)[7]))]

This has just read the ENTIRE CSV file, and captured the 8th row
(count starts at [0], so [7] is the 8th). Now, for EACH element in this
row you are performing...

<something>

which is....

[ [] for I in range(len(list(reader)[:10]))]

But since you have already read the entire CSV file, THIS "list(reader)"
should be returning None, and the first 10 elements on None is nothing
(or an error).
for numline, line in enumerate(reader):

As mentioned, you've already processed the entire CSV file in the
previous statements, so this loop also should perform exactly ZERO
times.

--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
B

Bruno Desthuilliers

Roman a écrit :

<ot>
Roman, please stop top-posting and learn to quote.
Bruno said:
Roman wrote:
(please dont top-post - corrected)
My intention is to create matrix based on parsed csv file. So, I
would like to have a list of columns (which are also lists).

csv = [
['L0C0', 'L0C1', 'L0C2'],
['L1C0', 'L1C1', 'L1C2'],
['L2C0', 'L2C1', 'L2C2'],
]

matrix = [[[] for l in range(len(csv))] for c in range(len(csv[0]))]

for numline, line in enumerate(csv):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

assert matrix == [
['L0C0', 'L1C0', 'L2C0'],
['L0C1', 'L1C1', 'L2C1'],
['L0C2', 'L1C2', 'L2C2']
]

> Thanks for spending so much time with me. I had since made the
> following change.
>
> matrix = [[[] for l in range(len(list(reader)[:10]))] for c in
> range(len(list(reader)[7]))]

Technically; this won't work. The first call to list(reader) will
consume reader.

It's also somewhat dumb (len(list(reader)[:10]) is always 10) and
inefficient (you're calling list(reader) twice, when you could call it
just once).

Instead of trying anything at random, read the fine manual and try to
understand the example I gave you.
> for numline, line in enumerate(reader):
> for numcol, col in enumerate(line):
> matrix[numcol][numline] = col
>
> print matrix
>
> I don't get mistakes anymore. However, still nothing gets printed

If you don't print anything, nothing will be printed.
 
R

Roman

below is the data I am trying to read

"000004" "AS0042123BO" "AS 0042.123 ROYAL ELONG SEAT
BO" "001610" "A/S Fixtures" 0 $99.00 3.70 "" "0042123" 11/20/2003
"000024" "AS0042001BK" "AS 0042.001 ROYAL EL*DISC BY
MFG*BK" "001610" "A/S
Fixtures" 0 $99.00 8.00 "723085611663" "0042001" 11/20/2003
"000104" "CH130TTWH" "CH 130TT EL PLAS SEAT C/F W/C
WH" "207067" "Church Seats" 12 $25.00 6.75 "073088079961" "130TT
000" 12/28/1995
"000112" "CH130TTBO" "CH 130TT EL PLAS SEAT C/F W/C
BO" "207067" "Church Seats" 23 $29.00 7.50 "073088079954" "130TT
006" 02/23/1998
"000124" "CH130TTSS" "CH 130TT EL PLAS SEAT C/F W/C
SS" "207067" "Church Seats" 14 $29.00 6.75 "073088079985" "130TT 162"
"000176" "XPT562" "PP T562" "201681" "Price
Pfister" 0 $233.50 0.00 "" "" 01/22/1998
"000180" "XPT564" "PP T564" "201681" "Price
Pfister" 0 $0.00 0.00 "" "" 07/19/1996
"000224" "MO5270" "MO 5270*DBM*MON BIDET FCT L/HDL
CP" "204938" "Moen" 0 $0.00 8.00 "026508050286" "005270"
"000236" "MO5270P" "MO 5270P*DBM*BIDET FCT LVR/HDL
PB" "204938" "Moen" 0 $0.00 8.00 "026508050309" "05270P"
"000240" "MO5275" "MO 5275 *DBM* BIDET FCT L/HDLS
CP" "204938" "Moen" 1 $0.00 8.00 "" "" 11/20/2003
"000244" "MO5275P" "MO 5275P*DBM* MON BIDET FCT
PB" "204938" "Moen" 0 $0.00 8.00 "026508050347" "05275P" 01/04/1996
"000248" "MO5201" "MO 5201 *DBM* TRAD BIDET LVR FCT
CP" "204938" "Moen" 0 $0.00 6.70 "026508050354" "5201" 01/04/1996
"000260" "MO5201P" "MO 5201P TRAD BIDET FCT
LVR/H*DBM*B" "204938" "Moen" 0 $0.00 7.00 "026508050378" "5201P" 01/04/1996
"000264" "MO5201W" "MO 5201W**DBM**IDET FCT LVR/HDL
WH" "204938" "Moen" 0 $0.00 6.70 "026508050385" "05201W" 01/04/1996
"066916" "FB1418AB" "FB D2418AB 18 TOWEL BAR
AB" "220502" "Liberty
Hardware" 0 $18.70 1.15 "079171141898" "D2418AB" 04/14/1998
"066920" "FBD2424AB" "FB D2424AB 24 TOWEL BAR
AB" "220502" "Liberty
Hardware" 39 $20.50 1.32 "079171242427" "D2424AB"
"066956" "P7341FLC" "PP 734-1FLC*DBM* SNK FCT 1H L/SP
CP" "201681" "Price
Pfister" 0 $147.65 7.00 "038877420218" "7341FLC" 04/14/1998
"066960" "P7341FLW" "PP 734-1FLW FILT SNK FCT 1H L/SP
WH" "201681" "Price
Pfister" 0 $157.99 7.00 "038877420225" "7341FLW" 04/14/1998
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:
It would help if you gave a sample of the input data (three lines
worth, say) AND an example of what the final output should be from those
three lines.
for col in line:
p[:0].append(str(col))

As has been pointed out, as soon as you used the [:0], you created a
local/temporary EMPTY slice of the original P, and you are appending one
column's value to this temporary, which is then thrown away.
import csv

-=-=-=-=-=-=-=- PROGRAM
p = []

fin = open("firearms.csv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter=",")

for line in [reader.next() for i in range(7)]:
p.append(line)

fin.close()
print p
-=-=-=-=-=-=-=- OUTPUT
[['Category', 'Model', 'Caliber', 'Serial #', 'Description',
'Accessories'], ['Air', 'Daisy 717 Pistol', '.177 pellet', '', '', ''],
['Air', 'Daisy/NRA PowerLine 953 Rifle', '.177 pellet', 'n/a',
'Micrometer Peep, "Globe" front (missing alternate inserts', 'Shooting
sling'], ['Air', 'RWS Diana Model 54 "Air King" Rifle', '.22 pellet',
'4022395', 'Hunting grade - >900fps', '2-7x BSA AOL scope'], ['Air',
'Gamo/NRA', '0.177', '', 'Hunting grade - ~1000fps; NRA markings on
barrel, stock', '4x (BSA?) AOL scope, NRA badge'], ['Air',
'Walther/Crossman CP99 Pistol', '.177 pellet', '', 'CO2, repeater
(currently magazine jams trigger/safety)', ''], ['Percussion', '? New
Orleans Ace boot-pistol', '.36 lead', '', '', '']]
-=-=-=-=-=-=-=- INPUT (just first seven lines)
Category,Model,Caliber,Serial #,Description,Accessories
Air,Daisy 717 Pistol,.177 pellet,,,
Air,Daisy/NRA PowerLine 953 Rifle,.177 pellet,n/a,"Micrometer Peep,
""Globe"" front (missing alternate inserts",Shooting sling
Air,"RWS Diana Model 54 ""Air King"" Rifle",.22 pellet,4022395,Hunting
grade - >900fps,2-7x BSA AOL scope
Air,Gamo/NRA,0.177,,"Hunting grade - ~1000fps; NRA markings on barrel,
stock","4x (BSA?) AOL scope, NRA badge"
Air,Walther/Crossman CP99 Pistol,.177 pellet,,"CO2, repeater (currently
magazine jams trigger/safety)",
Percussion,? New Orleans Ace boot-pistol,.36 lead,,,



But your explanations are unclear... Maybe you wanted the first
sublist to be all the first column, etc.

-=-=-=-=-=-=-=- PROGRAM
import csv

p = None

fin = open("firearms.csv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter=",")

for line in [reader.next() for i in range(7)]:
if not p:
p = [[] for j in range(len(line))]
for c in range(len(line)):
p[c].append(line[c])

fin.close()
print p
-=-=-=-=-=-=-=- OUTPUT (same input)
[['Category', 'Air', 'Air', 'Air', 'Air', 'Air', 'Percussion'],
['Model', 'Daisy 717 Pistol', 'Daisy/NRA PowerLine 953 Rifle', 'RWS
Diana Model 54 "Air King" Rifle', 'Gamo/NRA', 'Walther/Crossman CP99
Pistol', '? New Orleans Ace boot-pistol'], ['Caliber', '.177 pellet',
'.177 pellet', '.22 pellet', '0.177', '.177 pellet', '.36 lead'],
['Serial #', '', 'n/a', '4022395', '', '', ''], ['Description', '',
'Micrometer Peep, "Globe" front (missing alternate inserts', 'Hunting
grade - >900fps', 'Hunting grade - ~1000fps; NRA markings on barrel,
stock', 'CO2, repeater (currently magazine jams trigger/safety)', ''],
['Accessories', '', 'Shooting sling', '2-7x BSA AOL scope', '4x (BSA?)
AOL scope, NRA badge', '', '']]
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
D

Dennis Lee Bieber

below is the data I am trying to read
You don't show what you expect to have as the final result, but...

I've stuck in the pretty printer module to get easier read
-=-=-=-=-=-=- by column, first seven rows
import csv
import pprint

p = None

fin = open("sample.tsv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter="\t")

for line in [reader.next() for i in range(7)]:
if not p:
p = [[] for j in range(len(line))]
for c in range(len(line)):
p[c].append(line[c])

fin.close()
pprint.pprint(p)
-=-=-=-=-=-=-
[['000004', '000024', '000104', '000112', '000124', '000176', '000180'],
['AS0042123BO',
'AS0042001BK',
'CH130TTWH',
'CH130TTBO',
'CH130TTSS',
'XPT562',
'XPT564'],
['AS 0042.123 ROYAL ELONG SEAT BO',
'AS 0042.001 ROYAL EL*DISC BY MFG*BK',
'CH 130TT EL PLAS SEAT C/F W/C WH',
'CH 130TT EL PLAS SEAT C/F W/C BO',
'CH 130TT EL PLAS SEAT C/F W/C SS',
'PP T562',
'PP T564'],
['001610', '001610', '207067', '207067', '207067', '201681', '201681'],
['A/S Fixtures',
'A/S Fixtures',
'Church Seats',
'Church Seats',
'Church Seats',
'Price Pfister',
'Price Pfister'],
['0', '0', '12', '23', '14', '0', '0'],
['$99.00', '$99.00', '$25.00', '$29.00', '$29.00', '$233.50', '$0.00'],
['3.70', '8.00', '6.75', '7.50', '6.75', '0.00', '0.00'],
['', '723085611663', '073088079961', '073088079954', '073088079985',
'', ''],
['0042123', '0042001', '130TT 000', '130TT 006', '130TT 162', '', ''],
['11/20/2003',
'11/20/2003',
'12/28/1995',
'02/23/1998',
'01/22/1998',
'07/19/1996']]


and

-=-=-=-=-=-=- by row, first seven rows
import csv
import pprint

p = []

fin = open("sample.tsv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter="\t")

for line in [reader.next() for i in range(7)]:
p.append(line)

fin.close()
pprint.pprint(p)

-=-=-=-=-=-=-
[['000004',
'AS0042123BO',
'AS 0042.123 ROYAL ELONG SEAT BO',
'001610',
'A/S Fixtures',
'0',
'$99.00',
'3.70',
'',
'0042123',
'11/20/2003'],
['000024',
'AS0042001BK',
'AS 0042.001 ROYAL EL*DISC BY MFG*BK',
'001610',
'A/S Fixtures',
'0',
'$99.00',
'8.00',
'723085611663',
'0042001',
'11/20/2003'],
['000104',
'CH130TTWH',
'CH 130TT EL PLAS SEAT C/F W/C WH',
'207067',
'Church Seats',
'12',
'$25.00',
'6.75',
'073088079961',
'130TT 000',
'12/28/1995'],
['000112',
'CH130TTBO',
'CH 130TT EL PLAS SEAT C/F W/C BO',
'207067',
'Church Seats',
'23',
'$29.00',
'7.50',
'073088079954',
'130TT 006',
'02/23/1998'],
['000124',
'CH130TTSS',
'CH 130TT EL PLAS SEAT C/F W/C SS',
'207067',
'Church Seats',
'14',
'$29.00',
'6.75',
'073088079985',
'130TT 162'],
['000176',
'XPT562',
'PP T562',
'201681',
'Price Pfister',
'0',
'$233.50',
'0.00',
'',
'',
'01/22/1998'],
['000180',
'XPT564',
'PP T564',
'201681',
'Price Pfister',
'0',
'$0.00',
'0.00',
'',
'',
'07/19/1996']]


If you want only the first seven columns but all rows, try

for line in reader:
p.append(line[:7])
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
I

Iain King

Mike said:
Roman said:
Thanks for your help

My intention is to create matrix based on parsed csv file. So, I would
like to have a list of columns (which are also lists).

I have made the following changes and it still doesn't work.


cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt > 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1

print p

p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Try doing:

p[j] = p[j].append(col)

No, this doesn't work. append is an in-place operation, and you'll end
up setting p[j] to it's return, which is None.

Iain
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,174
Latest member
BlissKetoACV
Top