读取存储在文本文件中的元组
我一直在寻找一种在运行后也永久存储由 python 程序创建的元组的方法。因此,为了简单起见,我决定将该数据写入文本文件(或者是否有一些更优雅但简单的解决方案值得推荐?),
因此执行此操作的命令如下所示:
import codecs
txt = codecs.open("data.txt", "w", encoding="utf-8")
.
.
.
data = set1, set2, set3
print >> txt, data
生成一个文本文件,该文本文件看起来像
(u'name1', 'file1', 'date1')
(u'name2', 'file2', 'date2')
.
.
.
什么是正确的方法访问 data.txt 仅显示所有第二个数据集,例如“file1”、“file2”等?
我搞乱了 for 循环、read() 和 readline() 但从来没有得到文件中第二项的简单输出......我希望有人可以帮助我?
预先非常感谢!
I was looking for a way to permanently store tuples created by a python program also after runtime. So I just decided for simplicity to write that data into a textfile (or is there some much more elegant yet simple solution to recommend?)
so the command for doing that looks like:
import codecs
txt = codecs.open("data.txt", "w", encoding="utf-8")
.
.
.
data = set1, set2, set3
print >> txt, data
resulting in a textfile that looks like
(u'name1', 'file1', 'date1')
(u'name2', 'file2', 'date2')
.
.
.
what is the correct way to access data.txt only displaying all the second data-sets, in the example case 'file1', 'file2' etc?
I messed around with for loops, read() and readline() but never got to just a simple output of the second item in my file... I hope that someone can help me there?
thanks a lot in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑使用 pickle.dump 和 pickle.load 为您完成所有工作。如果您不介意文件采用 Python 特定格式,那么这是一个合理的选择。
还可以考虑使用 sqlite3 来存储数据。此格式可由其他程序读取并且可查询(即您可以仅检索文件名字段而不是整个记录)。
否则,读取直接文本转储的传统解决方案是逐行读取文件,解析或评估文本以将其转换回 Python 对象,然后提取感兴趣的字段:
Consider using pickle.dump and pickle.load to do all the work for you. That is a reasonable choice if you don't mind the file being in a Python specific format.
Also consider using sqlite3 to store the data. This format is readable by other programs and it is queryable (i.e. you can retrieve just the filename field instead of the entire record).
Otherwise, the traditional solution for a reading straight text dump is to read the file line-by-line, either parse or evaluate the text to convert it back into a Python object, and then extract the fields of interest:
考虑使用 pickle 按原样保存变量。
Consider using pickle to save the variables as they are.