2

My code to write my data in a .txt file:

with open(file_path, 'w') as f:
    id = 1
    for line in value:
        line = re.sub('[^A-Za-z0-9-,]+', '', str(line))
        ymax, xmax, xmin, ymin=line.split(',')
        f.write(('{{\'yMax\': u\'{}\', \'xMax\': u\'{}\', \'xMin\': u\'{}\',\'yMin\': u\'{}\', \'id\': \'{}\', \'name\': \'\'}}'.format(ymax, xmax, xmin, ymin,id)))
        id = id + 1

outcome :

{'yMax': u'156', 'xMax': u'4802', 'xMin': u'4770','yMin': u'141', 'id': '1', 'name': ''}
{'yMax': u'157', 'xMax': u'4895', 'xMin': u'4810','yMin': u'141', 'id': '2', 'name': ''}

However i want my data in a table like format of .csv:

image     id    name    xMin    xMax    yMin    yMax
1-0.png   1             4770    4802    141     156
1-0.png   2             4810    4895    141     157

How can i adjust my code to go from the .txt format i already have to the .csv format i want? The excess column which is image is simply the filename of the txt but .png instead of txt so easy enough using re i can adjust later my main issue is the table shape.

1 Answers1

2

This should help. use csv.DictWriter

with open(file_path, 'w') as f:
    writer = csv.DictWriter(f, delimiter='\t', fieldnames=['yMax', 'xMax', 'xMin', 'yMin', 'id', 'name'])      #Tab seperated
    writer.writeheader()    #Add header
    for i, line in enumerate(value, 1):             #enumerate to get id
        line = re.sub('[^A-Za-z0-9-,]+', '', str(line))
        ymax, xmax, xmin, ymin=line.split(',')
        d = {'yMax': ymax,'xMax': xmax, 'xMin': xmin,'yMin': ymin, 'id': i, 'name': ''}
        writer.writerow(d)

Note: This is sample code.

Rakesh
  • 75,210
  • 17
  • 57
  • 95