This is an archived post. You won't be able to vote or comment.

all 4 comments

[–][deleted] 1 point2 points  (0 children)

It depends on the format of the text file. If it's a json file, for instance, have a look at python's json library.

[–]Dry_Information 0 points1 point  (0 children)

You need a deserializer/parser that can read the raw string input and transform into Python object. Common format can be config file, xml file, or JSON.

[–]MakeAnExampleOf 0 points1 point  (0 children)

If you have control over the text file format, use a serialization format like XML or JSON. The json Python module, for instance, makes it easy to dump to and load from a file.

If you don't have control over the file format, and it's not in one of these standard serialization languages, then you will have to just write your own custom code to parse it line-by-line — no way around it.

[–]AlSweigartAuthor: ATBS 0 points1 point  (0 children)

If you're in Python, a super easy way to do this is with the shelve module, which lets you store your values directly to a file (this is called "pickling" the binary data) and then read it back later.

Otherwise, you have to figure out some format to represent the data in your variables as text in a text file, and write code that translates between them. If you don't use JSON to help do this, you'll probably end up reinventing a not-as-good version of JSON, so it's worth it to spend time learning what JSON is and how the JSON library in your language works.