Home>

How can I write the following list line by line to a text file?

[['train_00000.jpg', 0, 53, 89, 224, 'Signs'],
 ['train_00001.jpg', 602, 456, 638, 480, 'Signs'],
 ['train_00002.jpg', 605, 482, 633, 514, 'Signs'],
['train_00003.jpg', 739, 590, 764, 644, 'Motorbike'],
 ['train_00004.jpg', 900, 558, 988, 663, 'Car'],
['train_00005.jpg', 1032, 570, 1107, 643, 'Car'],
 ['train_00006.jpg', 1102, 586, 1163, 635, 'Car']]

# Save
import pickle
f = open ('list.txt', 'wb')
pickle.dump (df, f)

I want to call it in the following way. Is there a way to save line by line and write line by line? Please professor

with open ("list.txt", 'r') as f:
    print ('Parsing annotation files')
    for line in f:
        line_split = line.strip (). split (',')
        (filename, x1, y1, x2, y2, class_name) = line_split

Error >>>
~/anaconda3/envs/tensorflow_p36/lib/python3.6/codecs.py in decode (self, input, final)
    319 # decode input (taking the buffer into account)
    320 data = self.buffer + input
->321 (result, consumed) = self._buffer_decode (data, self.errors, final)
    322 # keep undecoded input until the next call
    323 self.buffer = data [consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
  • Answer # 1

    df = [['train_00000.jpg', 0, 53, 89, 224, 'Signs'],
          ['train_00001.jpg', 602, 456, 638, 480, 'Signs'],
          ['train_00002.jpg', 605, 482, 633, 514, 'Signs'],
          ['train_00003.jpg', 739, 590, 764, 644, 'Motorbike'],
          ['train_00004.jpg', 900, 558, 988, 663, 'Car'],
          ['train_00005.jpg', 1032, 570, 1107, 643, 'Car'],
          ['train_00006.jpg', 1102, 586, 1163, 635, 'Car']]
    # Save
    with open ('list.txt', 'w +') as f:
        for d in df:
            f.write (','. join (map (str, d)) + '\ n')

Trends