Home > Back-end >  Writing a list of a list in a text file
Writing a list of a list in a text file

Time:03-04

I am trying to write a list of list to a text file but I am getting the following error:

Traceback (most recent call last):

 File "D:......", line 26, in <module>
file.write(items)
TypeError: write() argument must be str, not list

The code:

coordinates = []
for i, j in zip(x, y):
  coordinates.append([i,j])

file = open('coordinates.txt', 'w')
for items in coordinates:
  file.write(items)

The list: [[0, 17], [1, 5], [2, 12], [3, 9], [4, 7], [5, 7], [6, 4], [7, 6], [8, 6], [9, 16]]

If anyone would help me with this it would be much appreciated.

CodePudding user response:

Assuming your data will not be tampered with, you can do str(coordinates) and write it. Also Remember, to close it.

To retrieve it, do this

from ast import literal_eval
with f as open('coordinates.txt'):
    coordinates = literal_eval(f.read())

CodePudding user response:

This is the solution I found after following a previous comment by Fishball Noodles:

coordinates = []
for i, j in zip(x, y):
 coordinates.append((i,j))

file = open('coordinates.txt', 'w')
for items in coordinates:
 line = ' '.join(str(x) for x in items)
 file.write(line   '\n')
  • Related