1

I have a large list of lists like:

X = [['a','b','c','d','e','f'],['c','f','r'],['r','h','l','m'],['v'],['g','j']]

each inner list is a sentence and the members of these lists are actually the word of this sentences.I want to write this list in a file such that each sentence(inner list) is in a separate line in the file, and each line has a number corresponding to the placement of this inner list(sentence) in the large this. In the case above. I want the output to look like this:

1. a b c d e f
2. c f r
3. r h l m
4.v
5.g j

I need them to be written in this format in a "text" file. Can anyone suggest me a code for it in python? Thanks

2 Answers 2

5
with open('somefile.txt', 'w') as fp:
  for i, s in enumerate(X):
    print >>fp, '%d. %s' % (i + 1, ' '.join(s))
Sign up to request clarification or add additional context in comments.

3 Comments

or fp.write("{row}. {sentence}\n".format(row=i, sentence=' '.join(s))) if you don't like the >> print syntax.
There is a slight problem with that, the counter starts with 2 always!
print >>fp, '%d. %s' % (i, ' '.join(s)) i += 1 will do the job ;)
0
with open('file.txt', 'w') as f:
    i=1
    for row in X:
        f.write('%d. %s'%(i, ' '.join(row)))
        i+=1

4 Comments

You're missing the linebreaks.
enumerate is there for a reason.
I'm not sure that enumerate() will create generator object, so enumerate() can take a lot of memory/cpu for large lists. If enumerate() will create a generator, previous example can be preferable.
It's an easy thing to look up in the docs and/or test. enumerate: Return an enumerate object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.