打开CSV文件,并将每一行写入新的动态命名的CSV文件 [英] Open CSV file and writing each row to new, dynamically named CSV file

查看:130
本文介绍了打开CSV文件,并将每一行写入新的动态命名的CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含50行数据的csv文件,我想将其分成每行一个单独的csv文件,其中包括第一行(标题)和相关行.

I have a csv file with, say, 50 rows of data, and I would like to split it into separate csv files for each row, which includes first row (header) and the the relevant row.

例如 文件1包含:第1行,第2行, 文件2包含:第1行,第3行, 文件3包含:row1,row4

E.g. file 1 contains: row1, row2, file 2 contains: row1, row3, file 3 contains: row1, row4

以此类推.

当前与以下人员合作:

import csv

counter = 1

with open('mock_data.csv', 'r', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        filename = "file_%s" % str(counter)
        with open(filename, 'w') as csvfile_out:
            writer = csv.writer(csvfile_out)
            writer.writerow(row)
            counter = counter + 1

我当前未定义'csvfile_out'.

I'm currently getting 'csvfile_out' not defined.

a)我什至正确地解决了这个问题 b)为什么没有定义csvfile_out的任何想法?

a) Am I even approaching this correctly b) Any ideas why csvfile_out isn't being defined?

推荐答案

我已经尝试过了,它可以很好地满足您的目的.不幸的是,我没有得到任何csvfile_out error,并且您的 with语句在我的Python 2.7.12控制台中可以正常工作.

I have tried this and it works fine for your purpose. Unfortunately, I didn't get any csvfile_out error and your with statement works correctly in my Python 2.7.12 console.

import csv

counter = 1

with open('mock_data.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    row1 = next(reader) # here you save your first line of the .csv file
    for row in reader:
        if row: # if row is not empty, write a file with this row
            filename = "file_%s" % str(counter)
            with open(filename, 'w') as csvfile_out:
                writer = csv.writer(csvfile_out)
                writer.writerow(row1) #here you write your row1 as first row of csvfile_out
                writer.writerow(row)
                counter = counter + 1

这篇关于打开CSV文件,并将每一行写入新的动态命名的CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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