0

I have a file test.txt with this:

1.2.3.4 ['22', '9292', '9293']
1.2.3.5 ['232', '992']

I need to transform it in

1.2.3.4,22
1.2.3.4,9292
1.2.3.4,9293
1.2.3.5,232
1.2.3.5,922

What is the most pythonic way to do it?

2
  • 1
    "What is the most pythonic way to do it?" nice phrase but to me it sounds a little like "code it for me please?". Please at least try to solve the problem (open the file, iterate contents, make an attempt at solving the problem, etc) Commented Apr 8, 2014 at 20:59
  • 2
    Should the last two lines of the output be 1.2.3.4,232 and 1.2.3.4,992? Commented Apr 8, 2014 at 20:59

2 Answers 2

1
from ast import literal_eval
with open('filein.txt') as fIn, open('fileout.txt', 'w+') as fOut:
    for line in fIn:
        first, second = line.split(None, 1)
        for item in literal_eval(second):
            fOut.write('{},{}\n'.format(first, item))

Assuming that that list-part of each line is an actual valid Python list, we can use ast.literal_eval to safely parse it. So we just need to iterate over each line, split the first part from the list part, parse the list part. And then for each element in the list, we write a line to the target file.

Sign up to request clarification or add additional context in comments.

Comments

1

You can split each line on this regex: (?:\[|\]|, ), store element one of the split into a variable. Then iterate elements 2-and-up, and for each element print [element 1][comma][the next element].

Comments

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.