0

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!

3 Answers 3

1

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]))
Sign up to request clarification or add additional context in comments.

Comments

0
for s in allsets:
   for item in s:
     file_out.write("%s|" % item)
   file_out.write("\n")

\n changes the line.

2 Comments

Thanks! Is it possible to include the name of the set at the beginning of the string?
It is, if you can retrieve the name of the set from allsets. Say name_s is the name of the set s, you can add file_out.write("%s|"%name_s) in the outer loop, before the inner loop.
0

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'])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.