0

I want to save a list in python to a file which should be able to read later and added to a list variable in later use.

As an example

list = [42,54,24,65]

This should be written to a file as

[42,54,24,65] or
list = [42,54,24,65]

And should be able to read later from python for a later use and assign it to a list variable

Right now I'm using the following code.

    f = open('list_file', 'w')
    f.write(values)
    f.close()

This gives me an error

TypeError: write() argument must be str, not list

How can I fix this? Thanks

rksh
  • 3,920
  • 10
  • 49
  • 68
  • 1
    Saving and loading objects and using pickle: http://stackoverflow.com/q/4530611/584846 – Brent Washburne Mar 24 '16 at 17:21
  • Did you try `write(str(values))`? – OneCricketeer Mar 24 '16 at 17:21
  • @BrentWashburne I'm new to python, please could you tell me whether pickle is an external module that I have to install or something built in? – rksh Mar 24 '16 at 17:23
  • 1
    [`pickle`](https://docs.python.org/3.5/library/pickle.html?highlight=pickle#module-pickle) module is part of the standard python library, `import pickle`. Alternatively, you could write it out in `json` also part of the standard python library. – AChampion Mar 24 '16 at 17:27
  • @BrentWashburne Pickle will do the trick thanks :) – rksh Mar 24 '16 at 17:31

5 Answers5

1

If you just have a simple list, then you can use JSON and the json module.

import json
data = [42,54,24,65]

with open('output.txt', 'w') as f_out:
    json.dump(data, f_out)

with open('output.txt', 'r') as f_in:
    data2 = json.load(f_in)
print(data2) # [42,54,24,65]

And the contents of output.txt looks like

[42,54,24,65]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Any reason not to just use `json.dump(data, f_out)` and `data2 = json.load(f_in)` avoids converting to string. – AChampion Mar 24 '16 at 17:35
  • @AChampion Edited. I tried that initially, but couldn't remember the syntax. Had the file pointer in the wrong spot. – OneCricketeer Mar 24 '16 at 17:42
1

You could do it also with pickle, it works similarly to json, but it can serialize a broader set of Python objects than json. Json serializes text, and is human readable, while pickle serializes bytes, not human readable.

Consider this example:

import pickle, json

list_ = [42,54,24,65]

with open('list_file.pickle', 'wb') as fp, open('list_file.json', 'w') as fj:
    pickle.dump(list_, fp)
    json.dump(list_, fj)

with open('list_file.pickle', 'rb') as fp, open('list_file.json', 'r') as fj:
    list_unpickled = pickle.load(fp)
    list_from_json = json.load(fj)

print(list_unpickled) #[42, 54, 24, 65]
print(list_from_json) #[42, 54, 24, 65]

Notice that with pickle you have to open the files with the 'b' for binary reading/writing.

A side note: do not use variables with the same name as python keywords, like list.

According to 12.1.4 in the documentation:

The following types can be pickled:

  • None, True, and False
  • integers, floating point numbers, complex numbers
  • strings, bytes, bytearrays
  • tuples, lists, sets, and dictionaries containing only picklable objects
  • functions defined at the top level of a module (using def, not lambda)
  • built-in functions defined at the top level of a module
  • classes that are defined at the top level of a module
  • instances of such classes whose dict or the result of calling getstate() is picklable (see section Pickling Class Instances for details).
chapelo
  • 2,519
  • 13
  • 19
0

Map all values in the list to strings first, the write method only supports strings. E.g. list = list(map(str, list)) Also calling a variable "list" is a bad practice, use something like "ls" or whatever differs from standard Python keywords. If you want to use it later, you can just delimit the values using spaces. Just write it like f.write(" ".join(list)). Then, to read it back into a list, do list = f.readline().split() This, however, will keep the values in the list as strings, to get them back to ints, map again like list = list(map(int, list))

illright
  • 3,991
  • 2
  • 29
  • 54
0

According to the error in your code you passing a list to f.write().you need to pass string.

I assuming you want to write one word per line.try the code below it should work.

f = open('list_file', 'w')
for value in list:
       f.write(value+"\n")
f.close() 

To read later you can just open file again and read using this code:

f = open('list_file', 'r')
for line in f:
      print line.strip()
f.close() 
Denis
  • 1,219
  • 1
  • 10
  • 15
0

Turning my comment into an answer:

Try Saving and loading objects and using pickle:

import pickle
filehandler = open(b"Fruits.obj","wb")
pickle.dump(banana,filehandler)

To load the data, use:

file = open("Fruits.obj",'r')
object_file = pickle.load(file)
Community
  • 1
  • 1
Brent Washburne
  • 12,904
  • 4
  • 60
  • 82