Writing and Reading Using the codecs Module

An alternative to using the PyQt classes is to use Python's built-in and standard library classes for writing and reading text files. Files can be written and read directly using the file class, but if we want to specify the encoding, we must use the codecs module instead.

def saveText(self): error = None fh = None try:

fh = codecs.open(unicode(self._fname), "w", CODEC)

for key, movie in self._movies:

fh.write(u"{{MOVIE}} %s\n" % unicode(movie.title)) fh.write(u"%d %d %s\n" % (movie.year, movie.minutes, movie.acquired.toString(Qt.ISODate))) fh.write(u"{NOTES}") if not movie.notes.isEmpty():

fh.write(u"\n%s" % unicode(movie.notes)) fh.write(u"\n{{ENDMOVIE}}\n")

We have used exactly the same text format as we used when writing with a QTextStream, so the code is very similar to saveQTextStream(). We open the file using the codecs.open() function rather than the open() function; we do not have to specify a "binary" flag. We have omitted the code from the except block to the end since it is the same as we have seen before.

def loadText(self): error = None fh = None try:

fh = codecs.open(unicode(self._fname), "rU", CODEC)

self.clear(False) lino = 0 while True:

title = year = minutes = acquired = notes = None line = fh.readline() if not line:

raise ValueError, "no movie record found" else:

title = QString(line[len("{{MOVIE}}"):].strip())

We have shown only the first few lines of the loadText() method that corresponds to saveText(). This is because the method uses the same algorithm and almost the same code as the loadQTextStream() method. The only significant differences are due to the fact that we read in the lines as Python unicodes, so we must convert the title and notes to QStrings. Also, Python keeps the new-lines rather than discarding them, and returns an empty string to signify that the end of the file has been reached, so we must slightly modify the code to account for this. For the integers we can use Python's int() function rather than the intFromQStr() function we needed for QStrings.

We have chosen to read back in rU mode, which stands for "read universal newlines", rather than plain r mode, which stands for "read". This just means that the lines will be read correctly even if written on, say, Linux, and read back on say, Windows, even though the two operating systems use different line-ending conventions.

Was this article helpful?

0 0
Tuberminator

Tuberminator

The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook


Post a comment