pickle.dump 导出到文件
pickle.load 从文件读取
数据流格式为binary.
例子 :
[root@localhost ~]# vi test.py
import pickle
import sys
l_list = ['hello',['i',['am','digoal']]]
with open("/tmp/abc.txt", "wb") as f1:
pickle.dump(l_list, f1)
with open("/tmp/abc.txt", "rb") as f2:
new_list=pickle.load(f2)
print(new_list,file=sys.stdout)
输出
[root@localhost ~]# python test.py
['hello', ['i', ['am', 'digoal']]]
pickle的格式是binary的, 直接读取是一堆乱码.
[root@localhost ~]# cat /tmp/abc.txt
?]q(Xhelloq]q(Xiq]q(XamqXdigoalqeee.
[其他]
1.
2.
[参考]
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.
Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
Changed in version 3.3: Added the flush keyword argument.
2.
The strip() method removes unwanted whitespace from strings.
The file argument to the print() BIF controls where data is sent/saved.
The finally suite is always executed no matter what exceptions occur within a try/except statement.
An exception object is passed into the except suite and can be assigned to an identifier using the as keyword.
The str() BIF can be used to access the stringed representation of any data object that supports the conversion.
The locals() BIF returns a collection of variables within the current scope.
The in operator tests for membership.
The “+” operator concatenates two strings when used with strings but adds two numbers together when used with numbers.
The with statement automatically arranges to close all opened files, even when exceptions occur. The with statement uses the as keyword, too.
sys.stdout is what Python calls “standard output” and is available from the standard library’s sys module.
The standard library’s pickle module lets you easily and efficiently save and restore Python data objects to disk.
The pickle.dump() function saves data to disk.
The pickle.load() function restores data from disk.