[Python] save and read set, list, dict and other types

[Python] save and read set, list, dict and other types

1. set

To save and read Set objects, you can use the pickle module. The pickle module is the standard library in Python for serializing and deserializing objects. Here is a sample code:

1) Save the Set object to a file:

import pickle

my_set = {
    
    1, 2, 3, 4, 5}

# 保存Set对象到文件
with open('set.pkl', 'wb') as file:
    pickle.dump(my_set, file)

In the above code, we create a Set object my_set, and then use the pickle.dump() method to save the Set object to the file 'set.pkl'. We need to open the file in binary mode ('wb') for writing serialized objects.

2) Read the Set object in the file:

import pickle

# 从文件中读取Set对象
with open('set.pkl', 'rb') as file:
    my_set = pickle.load(file)

# 打印读取的Set对象
print(my_set)

In the above code, we use the pickle.load() method to read the Set object from the file 'set.pkl'. We need to open the file in binary mode ('rb') in order to read the deserialized objects.

2. list

Of course, you can also use the pickle module to save and read data types other than Set objects, such as List, Dict, etc. Here is sample code:

1) Save the List object to a file:

import pickle

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

# 保存List对象到文件
with open('list.pkl', 'wb') as file:
    pickle.dump(my_list, file)

In the above code, we create a List object my_list, and then use the pickle.dump() method to save the List object to the file 'list.pkl'.

2) Read the List object in the file:

import pickle

# 从文件中读取List对象
with open('list.pkl', 'rb') as file:
    my_list = pickle.load(file)

# 打印读取的List对象
print(my_list)

In the above code, we use the pickle.load() method to read the List object from the file 'list.pkl'.

3. Attention

The same approach can also be applied to other data types such as Dict, Tuple, etc.

Note that when using pickle to save and read objects, make sure the file is opened in binary mode ('wb' for saving, 'rb' for reading), this is because pickle serializes and unpacks in binary Serialized.

Guess you like

Origin blog.csdn.net/qq_51392112/article/details/131696594