我正在尝试将格式和文本附加到我的RTF文件的末尾。
我可以写入我的文件,但是添加不起作用。它使整个文档为空白。我对Python还是很陌生(比如5个小时),但是对于这种语言来说,这将是一个不错的项目。可能与正确刷新或关闭文档有关吗?或者甚至是通过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()
答案 0 :(得分:2)
您不需要使用“追加”和“写入”的单独模式打开文件,因为'a'
也可以用于新文件。但是,您仍然需要检查文件是否存在,因为如果存在,它将已经具有必需的RTF标头。因此,请检查此值并将其存储在布尔值中。
RTF文件以{\rtf
开头,并且始终必须以}
结尾,因此,如果要“末尾”添加一些内容,则必须删除最后一个字符。最简单的方法是将文件指针移到负号1并使用truncate
。然后,您可以添加任何有效的RTF序列(文件头除外,如果有的话),最后总是在末尾添加}
。
在代码中:
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('}')
(我还纠正了您的\fonttbl
代码,因此您可以使用\f1
将字体设置为格鲁吉亚。\fonttbl
只需要出现一次。)