Python Forum
Cut .csv to pieces and save as .csv
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cut .csv to pieces and save as .csv
#4
(Feb-13-2017, 09:29 AM)wavic Wrote: Just get the index of the first column and a slice for the second from the list generated for each .csv row.

If I understood correctly, he wish to have _one_ file for the _respective_ colum, that is: not a slice, but just this one column, and the next colum in another file?

And if the data amount is not too big, maybe one could do the datasplitting on a list generated from the source file and do the writing later as 'in one go' for each file?

Edit:
Something like this? I'm not sure how efficient it is for big data amounts, but for a small set, it seems to do what it should (except that it makes a needless file with the dates two times).
import csv
 
f = open("testcsv.csv")
csv_f = csv.reader(f, delimiter=',')

firstlinedone = False
listoffiles = []
for line in csv_f:

    # for the first line, make all files
    if firstlinedone == False:
        for columnumber, column in enumerate(line):
            newfilename = "test" + str(columnumber) + ".csv"
            # one can also do more formatting here for the filename
            newfile = open(newfilename, 'wb')
            listoffiles.append(newfile)
            firstlinedone == True
    for columnumber, column in enumerate(line):
        csvwriter = csv.writer(listoffiles[columnumber], delimiter = ',')
        csvwriter.writerow([line[0], line[columnumber]])

for anyfile in listoffiles:
    anyfile.close()
f.close()
Reply


Messages In This Thread
RE: Cut .csv to pieces and save as .csv - by wavic - Feb-13-2017, 09:29 AM
RE: Cut .csv to pieces and save as .csv - by merlem - Feb-13-2017, 09:48 AM
RE: Cut .csv to pieces and save as .csv - by buran - Feb-13-2017, 09:31 AM
RE: Cut .csv to pieces and save as .csv - by wavic - Feb-13-2017, 10:13 AM
RE: Cut .csv to pieces and save as .csv - by merlem - Feb-13-2017, 11:14 AM
RE: Cut .csv to pieces and save as .csv - by merlem - Feb-13-2017, 12:54 PM
RE: Cut .csv to pieces and save as .csv - by buran - Feb-13-2017, 03:05 PM
RE: Cut .csv to pieces and save as .csv - by merlem - Feb-13-2017, 08:15 PM
RE: Cut .csv to pieces and save as .csv - by buran - Feb-15-2017, 04:34 PM
RE: Cut .csv to pieces and save as .csv - by buran - Feb-16-2017, 11:03 AM
RE: Cut .csv to pieces and save as .csv - by buran - Feb-16-2017, 12:11 PM
RE: Cut .csv to pieces and save as .csv - by merlem - Feb-16-2017, 12:22 PM
RE: Converting a bunch of .csv to .txt - by buran - May-04-2017, 10:31 AM
RE: Converting a bunch of .csv to .txt - by buran - May-04-2017, 12:12 PM
RE: Converting a bunch of .csv to .txt - by Kebap - May-04-2017, 12:34 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020