1

So, I have a csv file. I just want to print the rows of the file as integers not in [ ]. My table of numbers looks like:

1 ; 0 ; 5 ; 10 ; 4 ; 3 ; 1 ; 7 ; 6 ; 11


1 ; 10 ; 4 ; 1 ; 1 ; 31 ; 0 ; 11 ; 0 ; 41


10 ; 4 ; 0 ; 12 ; 34 ; 2 ; 13 ; 3 ; 4 ; 4


2 ; 3 ; 6 ; 4 ; 5 ; 7 ; 8 ; 9 ; 11 ; 10


1 ; 2 ; 3 ; 12 ; 23 ; 24 ; 1 ; 2 ; 3 ; 4


1 ; 76 ; 3 ; 43 ; 54 ; 6 ; 5 ; 4 ; 3 ; 4


18 ; 12 ; 13 ; 14 ; 25 ; 34 ; 56 ; 43 ; 23 ; 23


34 ; 2 ; 5 ; 3 ; 3 ; 23 ; 23 ; 3 ; 2 ; 43


34 ; 32 ; 1 ; 5 ; 3 ; 23 ; 21 ; 3 ; 1 ; 3


1 ; 1 ; 2 ; 45 ; 2 ; 23 ; 1 ; 4 ; 1 ; 1


Now. My code looks like this.

import csv
with open('probeMitComma.csv','r+') as fin:
    read= csv.reader(fin, delimiter='\t')
    total = 0
    rows = list(read)
    print (rows[1],"\n",rows[2])

what I get is

['1', '10', '4', '1', '1', '31', '0', '11', '0', '41'] 
 ['10', '4', '0', '12', '34', '2', '13', '3', '4', '4']

I want to get those without [ ] and without ' '. I have tried with join (I get an error because it is with int)

beside this issue I also have another one. My full code looks like:

import csv
with open('probeMitComma.csv','r+') as fin:
    read= csv.reader(fin, delimiter='\t')
    total = 0
    rows = list(read)    #If I make this line and the one under as a comment it
    print (rows[1],"\n",rows[2])    #shows me the column that I want with the sum

    for col in read:
        print (col[0])
        total += int(col[0])
    print ("Total lautet " + str(total))

My real objective is to print each column with the respective sum and each row with the respective sum.

Erik Godard
  • 5,930
  • 6
  • 30
  • 33
A.Vladi
  • 13
  • 3
  • 2
    heads up, there is a glaring bug in your code: `rows = list(read)` exhausts the iterator. So when you do `for col in read:` the body of that for-loop is never executed, because `read` is done iterating. – juanpa.arrivillaga Jun 27 '17 at 19:54
  • Also, `read` returns rows... putting that in a variable called `col` is... – cs95 Jun 27 '17 at 19:56
  • 1
    Convert the ints to strings : `", ".join(map(str, row[0]))` – Bharat Jun 27 '17 at 19:57

1 Answers1

0

Taking advantage of the print() function:

print(*rows[1], sep=', ')
print(*rows[2], sep=', ')

gives you the desired output:

1, 10, 4, 1, 1, 31, 0, 11, 0, 41
10, 4, 0, 12, 34, 2, 13, 3, 4, 4

The help of the print() function:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • Thanks a lot it helped. There is one issue, I lost the first row (1 ; 0 ; 5 ; 10 ; 4 ; 3 ; 1 ; 7 ; 6 ; 11) although I used print(*rows[0], sep=', ') – A.Vladi Jun 27 '17 at 20:38