0

I have been scanning the internet searching for the best way to read a string list in a file. When writing to a file it gives me an error: TypeError: write() argument must be str, not list

So I made the list a string file.write(str([1,2,3])). So now in the file we have a string in the shape of a list so when reading this we will get [1, 2, 3]Note: This is a string not a list so we cannot acmes the elements. So I was wondering what would be the best way to read this line in the file as a LIST.

Using list(file.readline) I get something like ['[', '1', ',', ' ', '2', ',', ' ', '3', ']'] Thats not what I want

so I try splitting at the comma: print(line.split(',')) I get: ['[1', ' 2', ' 3]'] I could iterate through the first element in the list and the last and get rid of the brackets. But I don't think that is the best idea.

Does anyone know a better way of reading a str(list) in a file as a list?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I did post my code just in snippets would you like the entirety. It's not much of a problem, but a question. –  Aug 06 '20 at 18:19
  • Use a proper serialization format. For example, you can use pickle to serialize Python lists and other Python objects, or CSV for a general-purpose human-readable file. – Thomas Aug 06 '20 at 18:19

3 Answers3

0

The problem is that you are trying to write Python's String representation of a list to a file, rather than the raw list itself.

You could use JSON instead, which would be language independent

import json

l = ['1','2','3']

In [6]: with open('file.json', 'w') as f:
   ...:     json.dump(l,f)


In [7]: with open('file.json') as f:
   ...:     l = json.load(f)

In [8]: l
Out[8]: ['1', '2', '3']
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0
with open('your_file.txt') as f:
    content = eval(f.readline())
print(content)

This should work.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

Asuming that we have the python list of string and the targeted file is an .txt file then..

#Writing
input_array = [
    'hello there',
    'string 2',
    'python',
    'foo'
]

with open('file.txt', 'w+') as file:
    for line in input_array:
        file.writelines(line + '\n')

#Reading
output_array = []
with open('file.txt', 'r') as file:
    for line in file.readlines():
        output_array.append(line[:-1])

    print(output_array)

This is not the best solution but it will get the job done

Zetrext
  • 66
  • 2
  • Good solution but my question was what is the best solution:D So you saying this is not the best solution kinda defeats the purpous. –  Aug 06 '20 at 18:39
  • Np I wrote this solution having in mind fact that you want to use the txt file later – Zetrext Aug 06 '20 at 19:03