我是一名Python初学者,并且制作了一些基本脚本。我最近面临的挑战是采用一个非常大的csv文件(10gb +),并根据每行中特定变量的值将其分割成多个较小的文件。使用Python分割基于特定列的csv文件
例如,该文件可能是这样的:
Category,Title,Sales
"Books","Harry Potter",1441556
"Books","Lord of the Rings",14251154
"Series", "Breaking Bad",6246234
"Books","The Alchemist",12562166
"Movie","Inception",1573437
而且我希望将文件分割成单独的文件: Books.csv,Series.csv,Movie.csv
在现实中会有数百个类别,而且他们不会被排序。在这种情况下,他们在第一列,但将来他们可能不会。
我已经在网上找到了一些解决方案,但没有在Python中。有一个非常简单的AWK命令可以在一行中完成,但是我无法在工作中访问AWK。
我写了下面的代码,它可以工作,但我认为它可能是非常低效的。任何人都可以建议如何加快速度?
import csv
#Creates empty set - this will be used to store the values that have already been used
filelist = set()
#Opens the large csv file in "read" mode
with open('//directory/largefile', 'r') as csvfile:
#Read the first row of the large file and store the whole row as a string (headerstring)
read_rows = csv.reader(csvfile)
headerrow = next(read_rows)
headerstring=','.join(headerrow)
for row in read_rows:
#Store the whole row as a string (rowstring)
rowstring=','.join(row)
#Defines filename as the first entry in the row - This could be made dynamic so that the user inputs a column name to use
filename = (row[0])
#This basically makes sure it is not looking at the header row.
if filename != "Category":
#If the filename is not in the filelist set, add it to the list and create new csv file with header row.
if filename not in filelist:
filelist.add(filename)
with open('//directory/subfiles/' +str(filename)+'.csv','a') as f:
f.write(headerstring)
f.write("\n")
f.close()
#If the filename is in the filelist set, append the current row to the existing csv file.
else:
with open('//directory/subfiles/' +str(filename)+'.csv','a') as f:
f.write(rowstring)
f.write("\n")
f.close()
谢谢!
为什么不使用'pandas'? – Dadep