0

I have a list like this

a = ['h','a','i']

and I am printing the values of list in a file.

fo = open('file.txt','w')
    for i in a:
        fo.write(i)
    fo.close()

but i want the output like this,

1. h
2. a
3. i

which means I need to print the values with number bullet. How can I achieve this one.

I have tried with this code

count = 0

fo = open('file.txt','w')
        for i in a:
            count+=1
            fo.write("%s. %s"%(count,i))
        fo.close()

But if the string length in the list is high, the result is not coming with proper alignment.

I am getting output like

output I got

But i need the output like this

needed output

For example, if I have a string like this,

a = '<help>somthing data</help><help-error> something data </help-error><help-msg>some data</help-msg><help-info>some data</help-info>'

and I am trying with this code

fo=open('file.txt','w')
count = 0
if '<help-error>' in a:
    count+=1
    msg = re.search(r'<help-msg>(.*)</help-msg>',a).group()
    info = re.search(r'<help-info>(.*)</help-info>',a).group()
    fo.write("%s. %s\n"%(count,msg))
    fo.write("%s\n"%(info))

How can I achieve the same number bullet concept here.

sowji
  • 103
  • 10

4 Answers4

2

you can use enumerate:

>>> a = ['h','a','i']
>>> for i, x in enumerate(a):
...     print i, x
... 
0 h
1 a
2 i

enumerate returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
1

Use rjust() or change your formatting string (see code below).

And it is more "Pythonic" to use enumerate (see another answer for explanations what is does).

As I can see, you ARE getting the output the right way, BUT the editor you look at the output file at has automated LINE WRAPPING, so what you see is not how it is in file, right?

If you want to do line wrapping yourself in your code it needs introducing a logic and code of doing that, so it is a good idea to make an own attempt to accomplish it and if you then face problems just ask another question with the details of the issue with the code of your attempt.

a = ['h','a','i']
fo = open('file.txt','w')
for i, x in enumerate(a):
    # print( str(i).rjust(5)+'.', x )
    # print("%5s. %s"%(i,x))
    fo.write("%5s. %s"%(i,x))

fo.close()

# gives:
    1. a
    2. i
...
  123. x  

change rjust(5) or %5s to another value suiting your needs (max. length of expected number of items)

Claudio
  • 7,474
  • 3
  • 18
  • 48
1

As so often, there is a module for wrapping text, textwrap.

This code formats long lines with a leading count, a dot and a blank followed by the line of text. If the text is longer than a specified limit, the textwrap module inserts newlines and indents the new line beginnings:

import textwrap

def main():
    txt = ['Lorem ipsum est mi tincidunt diam aenean purus potenti.\n',
'Congue dictum et purus nisl ligula nam aliquam facilisis, morbi semper faucibus eget arcu semper consectetur, et rhoncus dictum vel ligula ornare morbi cursus ornare leo condimentum neque lacus.\n',
'Eu felis phasellus aliquam adipiscing luctus sodales praesent rhoncus donec habitant vel, vivamus aliquam venenatis tellus netus tempor suspendisse at tristique habitasse nunc at, tristique platea habitant ullamcorper velit litora.\n']

    with open('out.txt','w') as f:
        for lineno, line in enumerate(txt, 1):
            l = '{0:5d}. {1:s}'.format(lineno,line)
            l = textwrap.fill(l,initial_indent='', subsequent_indent=' '*7, width=80)
            f.write(l + '\n')

if __name__ == '__main__':
    main()

The margin here is set to 5 characters 0:05d with leading blanks. You set the subsequent_indent to this plus 2 to account for the dot and a space after the numeral. The width of the paragraph is 80 in this example.
The second argument to enumerate provides a starting value of 1.
The with open() syntax automatically closes the output file.

user1016274
  • 4,071
  • 1
  • 23
  • 19
0

Why don't you try the following and let me know if this worked or not.

a = ['h', 'a', 'i']
with open('file.txt', 'w') as f:
    for num, content in enumerate(a, 1):
        f.write(str(num) +". "+str(content))
        f.write("\n")

Please refer this regarding "with" in python

Community
  • 1
  • 1
d-coder
  • 12,813
  • 4
  • 26
  • 36
  • That doesn't solve the main problem, which was to wrap the text, and put the numbering in the margin. Your code still gives the same wrong output the OP was complaining about. – Thierry Lathuille Apr 18 '17 at 09:40