如何从CSV中获取特定表并在Python中编写新文件?

时间:2012-01-25 20:58:03

标签: python csv

我想从CSV文件中获取特定表,并为每个表返回一个文件。我有一些看起来像这样的东西:

France    city    population    agriculture
France    Paris    2000000      lots
France    Nice     500000      some


England   city    population    agriculture
England   London    30000       none
England   Glasgow    10000      some

我希望返回两个文件,一个用

France    city    population    agriculture
France    Paris    2000000      lots
France    Nice     500000      some

和另一个

England   city    population    agriculture
England   London    30000       none
England   Glasgow    10000      some

我该怎么做?

1 个答案:

答案 0 :(得分:2)

这是一个不使用cvs模块的解决方案(可以将csv模块分开表吗?)

with open('table.txt') as f:
    text = f.read()

tables = text.split('\n\n')

for itable,table in enumerate(tables):
    fileout = 'table%2.2i.txt' % itable
    with open(fileout,'w') as f:
        f.write(table.strip())
相关问题