Quoting through columns in CSV files in Python

I want to be able to use Python to open a .csv file as follows:

 5,26,42,2,1,6,6 

and then do some operation on them, like adding.

 total = 0 with open("file.csv") as csv_file: for row in csv.reader(csv_file, delimiter=','): for number in range(7): total += int(row[number]) 

The problem is that since the .csv file contains only one row and an unknown number of columns, I don’t know how to make this work without using hard coding or using really ugly code.

Is there a way to scroll columns with something like for columns in file in Python?

+4
source share
2 answers

You can just say

 for col in row: total += int(col) 

For instance:

 import csv from StringIO import StringIO total = 0 for row in csv.reader(StringIO("1,2,3,4")): for col in row: total += int(col) print total # prints 10 

The reason you can do this is because csv.reader returns a simple list for each line, so you can iterate over it like any other list in Python.

However, in your case, since you know that you have a file with one line of integers separated by commas, you can make this a lot easier:

 line = open("ints.txt").read().split(",") total = sum(int(i) for i in line) 
+8
source

You can iterate over a list of columns the same way you iterate over rows in a csv reader:

 total = 0 with open("file.csv") as csv_file: for row in csv.reader(csv_file, delimiter=','): for col in row: total += int(col) 

Or you can add the sum of each row in each pass and skip the inner loop:

 total = 0 with open("file.csv") as csv_file: for row in csv.reader(csv_file, delimiter=','): total += sum(map(int, row)) 

Or you can save the creation of an additional list using itertools.imap instead of map .

+3
source

Source: https://habr.com/ru/post/1304299/


All Articles