Reputation: 1129
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!
Upvotes: 3
Views: 2119
Reputation: 226376
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]
Upvotes: 5