栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从文件写入和读取列表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从文件写入和读取列表

如果您不需要它是人类可读/可编辑的,则最简单的解决方案是使用

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/617638.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号