'Writing a list of a list in a text file
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.
Solution 1:[1]
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())
Solution 2:[2]
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')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fishball Nooodles |
| Solution 2 | aniket32 |
