如何在python中将一个csv拆分为多个文件 [英] How to split one csv into multiple files in python

查看:1146
本文介绍了如何在python中将一个csv拆分为多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件(world.csv)如下:

I have a csv file (world.csv) looks like this :

"city","city_alt","lat","lng","country"
"Mjekić","42.6781","20.9728","Kosovo"
"Mjekiff","42.6781","20.9728","Kosovo"
"paris","42.6781","10.9728","France"
"Bordeau","16.6781","52.9728","France"
"Menes","02.6781","50.9728","Morocco"
"Fess","6.6781","3.9728","Morocco"
"Tanger","8.6781","5.9728","Morocco"

我想按国家将其拆分为多个文件:

And i want to split it to multiple file by country like this:

Kosovo.csv:

Kosovo.csv :

"city","city_alt","lat","lng","country"
"Mjekić","42.6781","20.9728","Kosovo"
"Mjekiff","42.6781","20.9728","Kosovo"

France.csv:

France.csv :

"city","city_alt","lat","lng","country"
"paris","42.6781","10.9728","France"
"Bordeau","16.6781","52.9728","France"

Morroco.csv:

Morroco.csv :

"city","city_alt","lat","lng","country"
"Menes","02.6781","50.9728","Morocco"
"Fess","6.6781","3.9728","Morocco"
"Tanger","8.6781","5.9728","Morocco"

推荐答案

如果不能使用熊猫,则可以使用内置的csv模块和itertools.groupby()函数.您可以使用它来按国家/地区分组.

If you can't use pandas you can use the built-in csv module and itertools.groupby() function. You can use this to group by country.

from itertools import groupby
import csv

with open('world.csv') as csv_file:
    reader = csv.reader(csv_file)
    next(reader) #skip header

    #Group by country
    lst = sorted(reader, key=lambda x : x[4])
    groups = groupby(lst, key=lambda x : x[4])

    for k,g in groups:
        filename = k + '.csv'
        with open(filename, 'w', newline='') as fout:
            csv_output  = csv.writer(fout)
            csv_output.writerow(["city","city_alt","lat","lng","country"])
            for line in g:
                csv_output.writerow(line)

这篇关于如何在python中将一个csv拆分为多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆