I have a list of tuples [(x,y,z),...,] and I want to store this list of tuples in a file. For this I chose a .txt file. I write to the file in the mode "wb" and then I close it. Later, I want to open the file in mode "rb" and convert this byte object back to a list of tuples. How would I go about this without regular expression nonsense? Is there a file type that would allow me to store this data and read it easily that I've overlooked?
Asked
Active
Viewed 529 times
1 Answers
1
The .txt
extension is typically not used for binary data, as you seem to intend.
Since your data structure is not known on a byte level, it's not that simple. If you do know your data (types and length), you could "encode" it as a binary structure with https://docs.python.org/3.4/library/struct.html and write that to a (binary) file.
Otherwise, there are many solutions to the problem of writing (structured) data to and reading data from files (that's why there are soo many file formats):
Standard library:
- https://docs.python.org/3/library/fileformats.html
- https://docs.python.org/3/library/persistence.html
- https://docs.python.org/3/library/xml.html
- https://docs.python.org/3/library/json.html
3rd party:
and other modules on https://pypi.python.org/
Related Q&A on Stackoverflow: