Python 如何将列表保存到文件并将其作为列表类型读取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27745500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:12:34  来源:igfitidea点击:

How to save a list to a file and read it as a list type?

pythonlistfilepython-3.xpickle

提问by Oceanescence

Say I have the list score=[1,2,3,4,5] and it gets changed whilst my program is running. How could I save it to a file so that next time the program is run I can access the changed list as a list type?

假设我有列表 score=[1,2,3,4,5] 并且在我的程序运行时它会发生变化。如何将其保存到文件中,以便下次运行程序时可以将更改后的列表作为列表类型访问?

I have tried:

我试过了:

score=[1,2,3,4,5]

with open("file.txt", 'w') as f:
    for s in score:
        f.write(str(s) + '\n')

with open("file.txt", 'r') as f:
    score = [line.rstrip('\n') for line in f]


print(score)

But this results in the elements in the list being strings not integers.

但这导致列表中的元素是字符串而不是整数。

采纳答案by Oceanescence

I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:

我决定不想使用泡菜,因为我希望能够在测试期间打开文本文件并轻松更改其内容。因此,我这样做了:

score = [1,2,3,4,5]

with open("file.txt", "w") as f:
    for s in score:
        f.write(str(s) +"\n")

with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

So the items in the file are read as integers, despite being stored to the file as strings.

所以文件中的项目被读取为整数,尽管作为字符串存储到文件中。

回答by Vivek Sable

You can use picklemodule for that. This module have two methods,

您可以pickle为此使用模块。这个模块有两种方法,

  1. Pickling(dump): Convert Python objects into string representation.
  2. Unpickling(load): Retrieving original objects from stored string representstion.
  1. Pickling(dump):将 Python 对象转换为字符串表示。
  2. Unpickling(load):从存储的字符串表示中检索原始对象。

https://docs.python.org/3.3/library/pickle.htmlcode:

https://docs.python.org/3.3/library/pickle.html代码:

>>> import pickle
>>> l = [1,2,3,4]
>>> with open("test.txt", "wb") as fp:   #Pickling
...   pickle.dump(l, fp)
... 
>>> with open("test.txt", "rb") as fp:   # Unpickling
...   b = pickle.load(fp)
... 
>>> b
[1, 2, 3, 4]

回答by Mike McKerns

pickleand other serialization packages work. So does writing it to a .pyfile that you can then import.

pickle和其他序列化包工作。将它写入一个.py文件,然后您可以导入该文件也是如此。

>>> score = [1,2,3,4,5]
>>> 
>>> with open('file.py', 'w') as f:
...   f.write('score = %s' % score)
... 
>>> from file import score as my_list
>>> print(my_list)
[1, 2, 3, 4, 5]

回答by Sarper Bilazer

If you don't want to use pickle, you can store the list as text and then evaluate it:

如果不想使用pickle,可以将列表存储为文本,然后对其进行评估:

data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
    file.write(str(data))

with open("test.txt", "r") as file:
    data2 = eval(file.readline())

# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

[0, 1, 2, 3, 4, 5] 类 'list' 类 'int'

[0, 1, 2, 3, 4, 5] 类 'list' 类 'int'

回答by Manideep Karthik

I am using pandas.

我正在使用熊猫。

import pandas as pd
x = pd.Series([1,2,3,4,5])
x.to_excel('temp.xlsx')
y = list(pd.read_excel('temp.xlsx')[0])
print(y)

Use this if you are anyway importing pandas for other computations.

如果您要为其他计算导入熊猫,请使用此选项。

回答by Manu Gond

If you want you can use numpy's save function to save the list as file. Say you have two lists

如果需要,您可以使用 numpy 的保存功能将列表保存为文件。假设你有两个列表

sampleList1=['z','x','a','b']
sampleList2=[[1,2],[4,5]]

here's the function to save the list as file, remember you need to keep the extension .npy

这是将列表保存为文件的功能,请记住您需要保留扩展名 .npy

def saveList(myList,filename):
    # the filename should mention the extension 'npy'
    np.save(filename,myList)
    print("Saved successfully!")

and here's the function to load the file into a list

这是将文件加载到列表中的函数

def loadList(filename):
    # the filename should mention the extension 'npy'
    tempNumpyArray=np.load(filename)
    return tempNumpyArray.tolist()

a working example

一个工作示例

>>> saveList(sampleList1,'sampleList1.npy')
>>> Saved successfully!
>>> saveList(sampleList2,'sampleList2.npy')
>>> Saved successfully!

# loading the list now 
>>> loadedList1=loadList('sampleList1.npy')
>>> loadedList2=loadList('sampleList2.npy')

>>> loadedList1==sampleList1
>>> True

>>> print(loadedList1,sampleList1)

>>> ['z', 'x', 'a', 'b'] ['z', 'x', 'a', 'b']

回答by Antonin GAVREL

What I did not like with many answers is that it makes way too many system calls by writing to the file line per line. Imho it is best to join list with '\n' (line return) and then write it only once to the file:

我不喜欢很多答案是它通过写入每行文件行来进行太多系统调用。恕我直言,最好用 '\n' (行返回)加入列表,然后只将它写入文件一次:

mylist = ["abc", "def", "ghi"]
myfile = "file.txt"
with open(myfile, 'w') as f:
    f.write("\n".join(mylist))

and then to open it and get your list again:

然后打开它并再次获取您的列表:

with open(myfile, 'r') as f:
    mystring = f.read()
my_list = mystring.split("\n")

回答by Jay Mody

You can also use python's jsonmodule:

您还可以使用 python 的json模块:

import json

score=[1,2,3,4,5]

with open("file.json", 'w') as f:
    # indent=2 is not needed but makes the file more 
    # human-readable for more complicated data
    json.dump(score, f, indent=2) 

with open("file.json", 'r') as f:
    score = json.load(f)

print(score)

The advantage of using a json is that:

使用 json 的优点是:

  1. The file is human readable
  2. Non-python programs can read and understand the json file
  3. You can literally save any list/dictionary in python to a json (as long as all the values are serializable, so most objects/functions can't be saved into a json)
  1. 该文件是人类可读的
  2. 非python程序可以读取和理解json文件
  3. 您可以将python中的任何列表/字典从字面上保存到json(只要所有值都是可序列化的,因此大多数对象/函数无法保存到json中)

Typically, you'll see jsons used for more complicated nested lists/dictionaries (like an array of records). The main disadvantage of storing your data as a json is that the data is stored in plain-text, and as such is completely uncompressed, making it a slow and bloated option for large amounts of data.

通常,您会看到 jsons 用于更复杂的嵌套列表/字典(如记录数组)。将数据存储为 json 的主要缺点是数据以纯文本形式存储,因此完全未压缩,因此对于大量数据而言,它是一个缓慢而臃肿的选择。