📅  最后修改于: 2020-11-07 08:22:45             🧑  作者: Mango
Python的内置open()函数返回的Python的内置文件对象有一个重要的缺点。当以“ w”模式打开时,write()方法仅接受字符串对象。
这意味着,如果您有以任何非字符串形式表示的数据,内置类(数字,字典,列表或元组)或其他用户定义类的对象,则无法将其直接写入文件。在编写之前,您需要将其转换为其字符串表示形式。
numbers=[10,20,30,40]
file=open('numbers.txt','w')
file.write(str(numbers))
file.close()
对于二进制文件, write()方法的参数必须是字节对象。例如,整数列表由bytearray()函数转换为字节,然后写入文件。
numbers=[10,20,30,40]
data=bytearray(numbers)
file.write(data)
file.close()
要从文件中读回相应数据类型的数据,需要进行反向转换。
file=open('numbers.txt','rb')
data=file.read()
print (list(data))
从对象到字符串或字节格式的这种手动转换(反之亦然)非常麻烦且繁琐。可以将字节序列形式的Python对象的状态直接存储到文件或内存流中,并恢复到其原始状态。此过程称为序列化和反序列化。
Python的内置库包含用于序列化和反序列化过程的各种模块。
Sr.No. | Name & Description |
---|---|
1 |
pickle Python specific serialization library |
2 |
marshal Library used internally for serialization |
3 |
shelve Pythonic object persistence |
4 |
dbm library offering interface to Unix database |
5 |
csv library for storage and retrieval of Python data to CSV format |
6 |
json Library for serialization to universal JSON format |