读取存储在文本文件中的元组

发布于 2024-12-13 11:00:03 字数 558 浏览 0 评论 0原文

我一直在寻找一种在运行后也永久存储由 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

草莓酥 2024-12-20 11:00:03

考虑使用 pickle.dumppickle.load 为您完成所有工作。如果您不介意文件采用 Python 特定格式,那么这是一个合理的选择。

还可以考虑使用 sqlite3 来存储数据。此格式可由其他程序读取并且可查询(即您可以仅检索文件名字段而不是整个记录)。

否则,读取直接文本转储的传统解决方案是逐行读取文件,解析或评估文本以将其转换回 Python 对象,然后提取感兴趣的字段:

for line in codecs.open("data.txt", "r", encoding="utf-8"):
    tup = ast.literal_eval(line)
    print tup[1]

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:

for line in codecs.open("data.txt", "r", encoding="utf-8"):
    tup = ast.literal_eval(line)
    print tup[1]
南汐寒笙箫 2024-12-20 11:00:03

考虑使用 pickle 按原样保存变量。

Consider using pickle to save the variables as they are.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文