简体   繁体   English

Python:逐行读取 CSV 并每行创建一个文件

[英]Python: read CSV row by row and create a file per row

Basically I want to read my CSV and create one text file per row.基本上我想阅读我的 CSV 并每行创建一个文本文件。
My CSV content is: Grenouille,1139,287,252,164,2017-03-04-21_35_19.jpg,1920,1080我的CSV内容为: Grenouille,1139,287,252,164,2017-03-04-21_35_19.jpg,1920,1080

I've done the following code:我已经完成了以下代码:

import sys
import csv

with open('labels_grenouilles.csv', newline='') as csvfile:
    spamreader = list(csv.reader(csvfile, delimiter=' ', quotechar='|'))
    for row in spamreader:
        f = open(str(spamreader[5]) + ".txt", "a")
        f.write(str(spamreader[0]) + " " + str(spamreader[1]) + " " + str(spamreader[2]) + " " + str(spamreader[3]) + " " + str(spamreader[4]))
        f.close()

but instead of creating each time a new file it creates something like that:但不是每次都创建一个新文件,而是创建类似的东西:
在此处输入图像描述

What am I missing?我错过了什么?

I see you're using the for loop for each element of spamreader .我看到您正在对spamreader的每个元素使用for循环。 In this case, your spamreader is a list, so if you use spamreader[5] to create a file you'll get the same value everytime, since you're using the 6th element of the list everytime in open() .在这种情况下,您的spamreader是一个列表,因此如果您使用spamreader[5]创建一个文件,您每次都会得到相同的值,因为您每次都在open()中使用列表的第 6 个元素。

Also using append in (open(spamreader[5], "a") this will create the file if it doesn't exist or will simply add at the end of its content if it exists.同样在(open(spamreader[5], "a")中使用append ) 如果文件不存在,则将创建该文件,如果存在,则将其简单地添加到其内容的末尾。

So, in conclusion, you're opening the same file everytime because you're using spamreader[5] in the for loop, and that's the same value everytime.因此,总而言之,您每次都打开同一个文件,因为您在for循环中使用spamreader[5] ,并且每次都是相同的值。

My guess is that you want to use row in open() instead of spamreader我的猜测是你想在open()中使用row而不是spamreader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM