Saving and Loading Text Files

PyQt and the Python standard library provide facilities for writing and reading text files. PyQt uses the QTextStream class, and the Python standard library uses the codecs module.

Plain text formats are usually human-readable, in a text editor, for example, and are usually easy to write. Any kind of data can be written as plain text one way or another. Numbers and dates can be written quite easily and compactly by using their string representations, and other types, such as images, can be written in more verbose forms—for example, using .xpm format.

Reading plain text that includes nontextual data or that has structure (for example, a record structure) means that we must write a parser, and this can be quite difficult, especially for complex data or complex data structures. Plain text formats can also be quite tricky to extend in a way that remains compatible with earlier formats, and they are vulnerable to being misread due to differences between the encoding read and the encoding written, since a user might edit them using a text editor that assumes a different encoding from the one that was actually used. These formats are most useful for simple file structures that store simple data types.*

Format Example

{{MOVIE}} LI title J {{MOVIE}} 12 Monkeys year u minutes u acquired J 1995 129 2001-06-21

notes J Based on La Jetée

Figure 8.4 The My Movies text format

The data we need to write contains only simple types: strings, integers, and a date. But we still need to structure the text file so that each movie record can be distinguished, and we must account for the fact that the notes text may extend over multiple lines.

The structure we have chosen is shown in Figure 8.4. In the Format column on the left, spaces are indicated by u and newlines by J.

The notes may span multiple lines, but we have assumed that no line of notes begins with the text {{ENDMOVIE}}. A more robust solution would in-

★If the format is very simple, it may be easiest to use a QSettings object and have it read and write to a specified file rather than to hand-code.

volve escaping. For example, we could assume that for any line that begins with, say, \, we ignore the \ and take the rest of the line as literal text. This would allow us to include a line with the text {{ENDMOVIE}}", by writing it as \{{ENDMOVIE}}.

Was this article helpful?

0 0
100 SEO Tips and More

100 SEO Tips and More

100 SEO Tips EVERY SEO Enthusiast Should Know. This Report 100 SEO Tips will help you to Utilize These Tips to Dominate The Search Engine Today.

Get My Free Ebook


Post a comment