简体   繁体   English

使用Python从文件中写入和读取列表

[英]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. 我想将python中的列表保存到一个文件,该文件以后应该可以读取,并添加到列表变量中以备后用。

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 并且应该能够稍后从python中读取以供以后使用并将其分配给列表变量

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. 如果只有一个简单列表,则可以使用JSON和json模块。

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 并且output.txt的内容看起来像

[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. 您也可以使用pickle做到这一点,它的工作方式类似于json,但是它可以序列化比json更广泛的Python对象集。 Json serializes text, and is human readable, while pickle serializes bytes, not human readable. Json对文本进行序列化,并且易于阅读,而pickle对字节进行序列化,而不易于阅读。

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. 注意,使用pickle,您必须打开带有“ b”的文件以进行二进制读/写。

A side note: do not use variables with the same name as python keywords, like list . 注意:请勿使用与python关键字同名的变量,例如list

According to 12.1.4 in the documentation: 根据文档中的12.1.4:

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) 在模块顶层定义的功能(使用def,而不是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). 这样的类,其字典有getstate调用(的结果)是picklable的实例(见节酸洗类实例的详细信息)。

Map all values in the list to strings first, the write method only supports strings. 首先将列表中的所有值映射到字符串, write方法仅支持字符串。 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. 例如, list = list(map(str, list))另外,调用变量“ list”也是一种不好的做法,请使用“ ls”之类的名称或与标准Python关键字不同的名称。 If you want to use it later, you can just delimit the values using spaces. 如果以后要使用它,则可以使用空格来分隔值。 Just write it like f.write(" ".join(list)) . 就像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)) 然后,要将其读回到列表中,请执行list = f.readline().split() ,但是,这会将列表中的值保留为字符串,以使它们返回为整数,再次像list = list(map(int, list))

According to the error in your code you passing a list to f.write().you need to pass string. 根据代码中的错误,您将列表传递给f.write()。您需要传递字符串。

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 : 尝试保存和加载对象并使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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