[Tutor] Read and write list on I file

Steven D'Aprano steve at pearwood.info
Sat Jan 26 20:52:32 CET 2013


On 26/01/13 20:21, jarod_v6 at libero.it wrote:

(edited slightly to make it more clear)

> HI there!!!
> I have a file like this:
>
> 12345-2 ppppp
> 12389-4 iiiii
>
> I want to read  this file and organize in different way: The second number
> present  after "-" mean the times are ripetuted the elements..so in the
> example In the end I want to  have this result
>
> 12345-1 ppppp
> 12345-2 ppppp
> 12389-1 iiiii
> 12389-2iiiii
> 12389-3iiiii
> 12389-4iiiii
>
> Someone have a suggestion how to do this simple task..

Untested, but this should work. Adding error checking is left up to you.


f = open('file.txt', 'r')
# each line looks like:
#     ddddd-d ccc...
# where d is a digit and c is any non-space character.

for line in f:
     head, tail = line.split(' ')
     head, num = head.split('-')
     num = int(num)
     for i in range(1, num+1):
         print "%s-%s %s" % (head, i, tail)

f.close()



-- 
Steven


More information about the Tutor mailing list