Robby
Robby

Reputation: 23

Appending RTF formatting styles

I'm trying to append formatting and text to the end of my RTF file.

I'm able to write to my file ok, but appending doesn't work. It makes the entire document blank. I'm still really new to Python (like 5 hours new), but this would be a good project for this language. Possibly it has to do with flushing or closing the document correctly? Or maybe even the syntax for appending through r''?

import os

filename = 'list.rtf'

if os.path.exists(filename):
    append_write = 'a'
else:
    append_write = 'w'

myfile = open(filename,append_write)
myfile.write(r'{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset1 Arial;}}')
myfile.write(r'\b People \b0\line')
myfile.write(r'{\fonttbl{\f0\fswiss\fcharset1 Georgia;}}')
myfile.write(r'\i John \i0\line')
myfile.close()

Upvotes: 1

Views: 854

Answers (1)

Jongware
Jongware

Reputation: 22457

You don't need to open with separate modes for 'append' and 'write', as 'a' will also work with new files. However, you still need to check if the file exists, because if it does it will already have the mandatory RTF header. So check and store this value in a boolean.

An RTF file begins with {\rtf and always must end with a }, so if you want to add something "at the end", you must remove the final character. The easiest way is to move the file pointer to the end minus 1 and use truncate. Then you can add any valid RTF sequence (except for the file header, if there is one), and finally always add the } at the end.

In code:

import os
filename = 'list.rtf'
writeHeader = not os.path.exists(filename)

with open(filename,'a') as myfile:
    if writeHeader:
        myfile.write(r'{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset1 Arial;}{\f1\fswiss\fcharset1 Georgia;}}')
    else:
        myfile.seek(-1,2)
        myfile.truncate()
    # your new text comes here
    myfile.write(r'\b Bob \b0\line')
    myfile.write(r'\f1\i Fred \i0\line')
    # all the way to here
    # and then write the end marker
    myfile.write('}')

(I also corrected your \fonttbl code so you can set the font to Georgia with \f1. \fonttbl only needs to occur once.)

Upvotes: 2

Related Questions