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
Video Traffic Guru

Video Traffic Guru

You Can Drive THOUSANDS of Hungry Buyers to Your Offer. Over the last few months I've seen hundreds of video marketers struggle to make good money. Even though they put out video after video, they just aren't getting the kind of passive income they'd always wanted.

Get My Free Ebook

Post a comment