python – Output specific columns from csv

Question:

There is a csv file with named columns of the form:

id;name;address;zip
1;vasya;moscow;11111
2;oleg;sochi;22222

How can I display only columns using the standard csv module , for example name and zip? In the future, you need to create a new csv file with only these two columns.

Answer:

Thought it might be useful for someone:

import csv

with open('f_name', 'r') as f:
    incl_col = [1, 3]                          # индексы нужных столбцов
    new_csv = []                              # новый список для нового файла
    reader = csv.reader(f, delimiter=";")
    for row in reader:
        col = list(row[i] for i in incl_col)
        print(col)                            # вывод нужных столбцов
        new_csv.append(col)                   # заполняем новый список нужными столбцами

with open('new.csv', 'w') as f:               # создаем новый файл
    writer = csv.writer(f, delimiter=";")
    writer.writerows(new_csv)
Scroll to Top