Reputation: 5873
I am looking to read and write python zip lists - but I am not able to find excatly how to acheive ethis. So, I have the following:
zipofalllists=zip([a],[b],[c],[d],[e]..)
where [a],[b],[c],[d],[e] are just lists (mix made of strings, integers and floats) of equal dimension.
Now, id like to write and read this zip list to/from a text file. I was thinking of writing the zipofalllists as a csv at first - but I am not sure this is the right approach.
So, I have something like:
with open("master_csv_file.csv", "wb") as f:
fileWriter = csv.writer(f, delimiter='|',quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in zip(*masterzip):
fileWriter.writerow(row)
but.. I am not sure this is the right approach. This way I do get a csv file, but I am unsure also on how to read and unpack this csv back to the original lists (newbie here - please excuse this 101 question).
Confused as to what is the best/fool proof approach here.
Upvotes: 1
Views: 1855
Reputation: 43870
json
is nice, or pickle
.
import json
zipofalllists=zip([a],[b],[c],[d],[e])
# write
with open("out.json", "w") as out_f:
json.dump(zipofalllists, out_f)
# read
with open("out.json", "r") as in_f:
alllists = json.load(in_f)
Both pickle
and json
use load([file object])
for read and dump([object], [file object])
for writes directly from/to a file. You can also use loads()
anddumps()
to directly transfer an object to/from it's string representation.
Upvotes: 1
Reputation: 5147
James,
So what you're doing is completely independent from zipping the lists together. Basically, after you zip the lists, you have a new list that consists of more lists.
After that, you want to save it to a file. Since you have successfully zipped the lists, I assume writing the data structure to a file is what you want.
The easiest way to do this is to 'pickle' the data structure into a file so you can pull it back at a later date - see this link: enter link description here for more info.
Good luck - if it's something else you want to do, let me/us know.
Upvotes: 1