Reputation: 173
I am a python novice. I have a bunch of sets which are included in the list 'allsets'. In each set, I have multiple string elements. I need to print all of my sets in a text file, however, I would like to find a way to separate each element with a '|' and print the name of the set at the beginning. E.g.:
s1= [string1, string2...]
s2= [string3, string4...]
allsets= [s1,s2,s3...]
My ideal output in a text file should be:
s1|string1|string2
s2|string3|string4
This is the code I've written so far but it returns only a single (wrong) line:
for s in allsets:
for item in s:
file_out.write("%s" % item)
Any help? Thanks!
Upvotes: 0
Views: 229
Reputation: 4708
Have a look at the CSV module. IT does everything for you
Here's an example from the documentation
import csv
with open('eggs.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Upvotes: 0
Reputation: 400039
Those are not "sets", in Python, they're just lists.
The names of the variables (s1
and so on) are not easily available programmatically, since Python variables are ... weird. Note that you can have the same object given multiple names, so it's not obvious that there is a single name.
You can go around this by using a dictionary:
allsets = { "s1": s1, "s2": s2, ...}
for k in allsets.keys():
file_out.write("%s|%s" % (k, "|".join(allsets[k]))
Upvotes: 1
Reputation: 423
for s in allsets:
for item in s:
file_out.write("%s|" % item)
file_out.write("\n")
\n changes the line.
Upvotes: 0