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?
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.
1.2.3.4,232and1.2.3.4,992?