简体   繁体   中英

Writing and reading a list from a file in Python

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

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]

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).

Map all values in the list to strings first, the write method only supports strings. Eg 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))

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() 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM