Python: 逐行读取 CSV 并每行创建一个文件
Python: read CSV row by row and create a file per row
基本上我想读取我的 CSV 文件并每行创建一个文本文件。
我的 CSV 内容是:Grenouille,1139,287,252,164,2017-03-04-21_35_19.jpg,1920,1080
我完成了以下代码:
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()
但不是每次都创建一个新文件,而是创建类似的东西:
我错过了什么?
我看到您正在为 spamreader
的每个元素使用 for
循环。在这种情况下,你的 spamreader
是一个列表,所以如果你使用 spamreader[5]
创建一个文件,你每次都会得到相同的值,因为你每次都在 open()
.
同时在 (open(spamreader[5], "a")
中使用 append
如果文件不存在,这将创建文件,如果文件存在,将简单地添加到其内容的末尾。
所以,总而言之,您每次都打开同一个文件,因为您在 for
循环中使用了 spamreader[5]
,而且每次都是相同的值。
我的猜测是您想在 open()
中使用 row
而不是 spamreader
基本上我想读取我的 CSV 文件并每行创建一个文本文件。
我的 CSV 内容是:Grenouille,1139,287,252,164,2017-03-04-21_35_19.jpg,1920,1080
我完成了以下代码:
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()
但不是每次都创建一个新文件,而是创建类似的东西:
我错过了什么?
我看到您正在为 spamreader
的每个元素使用 for
循环。在这种情况下,你的 spamreader
是一个列表,所以如果你使用 spamreader[5]
创建一个文件,你每次都会得到相同的值,因为你每次都在 open()
.
同时在 (open(spamreader[5], "a")
中使用 append
如果文件不存在,这将创建文件,如果文件存在,将简单地添加到其内容的末尾。
所以,总而言之,您每次都打开同一个文件,因为您在 for
循环中使用了 spamreader[5]
,而且每次都是相同的值。
我的猜测是您想在 open()
中使用 row
而不是 spamreader