如果您不需要它是人类可读/可编辑的,则最简单的解决方案是使用
pickle。
来写:
with open(the_filename, 'wb') as f: pickle.dump(my_list, f)
读书:
with open(the_filename, 'rb') as f: my_list = pickle.load(f)
如果您 确实 需要使它们易于阅读,则我们需要更多信息。
如果
my_list保证是没有嵌入换行符的字符串列表,则只需每行写一个:
with open(the_filename, 'w') as f: for s in my_list: f.write(s + 'n')with open(the_filename, 'r') as f: my_list = [line.rstrip('n') for line in f]如果它们是Unipre字符串而不是字节字符串,则需要
enpre它们。(或者,更糟糕的是,如果它们是字节字符串,但不一定使用与系统默认设置相同的编码。)
如果它们可能包含换行符或不可打印的字符等,则可以使用转义或引号。Python在stdlib中内置了各种不同的转义。
让我们使用
unipre-escape此处一次解决以上两个问题:
with open(the_filename, 'w') as f: for s in my_list: f.write((s + u'n').enpre('unipre-escape'))with open(the_filename, 'r') as f: my_list = [line.depre('unipre-escape').rstrip(u'n') for line in f]您还可以在2.x中将3.x样式的解决方案与
precs模块或
io模块一起使用:*
import iowith io.open(the_filename, 'w', encoding='unipre-escape') as f: f.writelines(line + u'n' for line in my_list)with open(the_filename, 'r') as f: my_list = [line.rstrip(u'n') for line in f]
- TOOWTDI,那么哪种方法是显而易见的?这取决于…对于简短版本:如果您需要使用2.6之前的Python版本,请使用
precs
;如果不是,请使用io
。



