views:

48

answers:

2

Hi, 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

+5  A: 
with open('somefile.txt', 'w') as fp:
  for i, s in enumerate(X):
    print >>fp, '%d. %s' % (i + 1, ' '.join(s))
Ignacio Vazquez-Abrams
or `fp.write("{row}. {sentence}\n".format(row=i, sentence=' '.join(s)))` if you don't like the `>>` print syntax.
katrielalex
There is a slight problem with that, the counter starts with 2 always!
Hossein
print >>fp, '%d. %s' % (i, ' '.join(s)) i += 1 will do the job ;)
Hossein
A: 
with open('file.txt', 'w') as f:
    i=1
    for row in X:
        f.write('%d. %s'%(i, ' '.join(row)))
        i+=1
seriyPS
You're missing the linebreaks.
Ignacio Vazquez-Abrams
`enumerate` is there for a reason.
katrielalex
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.
seriyPS
@seriyPS: It's an easy thing to look up in the docs and/or test. `enumerate`: [Return an enumerate object.](http://docs.python.org/library/functions.html#enumerate)
bstpierre