Это пример моего CSV-файла:
04/Feb/2016:06:38:44-0500,ab,3,10,57,200,10254
04/Feb/2016:06:39:07-0500,cd,1,42,168,304,0
04/Feb/2016:06:39:07-0500,ef,1,43,169,304,0
04/Feb/2016:06:39:07-0500,ab,1,43,170,304,0
04/Feb/2016:06:39:07-0500,cd,1,44,171,304,0
04/Feb/2016:06:39:07-0500,ef,1,45,172,304,0
Я хотел бы получить строку во 2-м столбце, создать файл, названный как эта строка, если файл уже не существует и добавить эту конкретную строку в файл. Так что-то вроде этого:
fetch string in 2nd column -> "ab" -> if file doesnt exist create file called "ab.csv" -> open file and add line "04/Feb/2016:06:38:44-0500,ab,3,10,57,200,10254"
fetch string in 2nd column -> "cd" -> if file doesnt exist create file called "cd.csv" -> open file and add line "04/Feb/2016:06:39:07-0500,cd,1,42,168,304,0"
fetch string in 2nd column -> "ef" -> if file doesnt exist create file called "ef.csv" -> open file and add line "04/Feb/2016:06:39:07-0500,ef,1,43,169,304,0"
fetch string in 2nd column -> "ab" -> if file doesnt exist create file called "ab.csv" -> open file and add line "04/Feb/2016:06:39:07-0500,ab,1,43,170,304,0"
fetch string in 2nd column -> "cd" -> if file doesnt exist create file called "cd.csv" -> open file and add line "04/Feb/2016:06:39:07-0500,cd,1,44,171,304,0"
fetch string in 2nd column -> "ef" -> if file doesnt exist create file called "ef.csv" -> open file and add line "04/Feb/2016:06:39:07-0500,ef,1,45,172,304,0"
Результат:
ab.csv:
04/Feb/2016:06:38:44-0500,ab,3,10,57,200,10254
04/Feb/2016:06:39:07-0500,ab,1,43,170,304,0
----------------------------------------------
cd.csv:
04/Feb/2016:06:39:07-0500,cd,1,42,168,304,0
04/Feb/2016:06:39:07-0500,cd,1,44,171,304,0
----------------------------------------------
ef.csv:
04/Feb/2016:06:39:07-0500,ef,1,43,169,304,0
04/Feb/2016:06:39:07-0500,ef,1,45,172,304,0
Любая помощь appriciated!
Я не знаю, все ли вы ищете питоновское решение. Я поражен простотой в ответе steeldriver, не понял, что awk настолько силен.
#!/usr/bin/env python
import csv
import os
def main():
with open("file.csv", "rb") as f:
reader = csv.reader(f)
for row in reader:
fname = row[1] + ".csv"
with open(fname, 'w') as f:
f.write(','.join([i for i in row]))
main()
Нельзя винить меня за попытку: D для блестящей награды