文件中的 Python 写入命令不给出输出(rtf 文件输出)

xiaoxingxing python 217

原文标题Python write command in file does not give output (rtf file output)

我是这个平台和 python 的新手。我正在尝试使用写入命令在 rtf 文件中输入值,但它只需要第一个写入命令,并且只有在我使用字体命令时才需要另一个。

a = r"C:\Users\XYZ/test/abc.rtf"
Subject = "ABC 123 "
Prepared = " XYZ 456"
with open(a, 'w') as file:
    file.write("{\\rtf1 \\qc \\fs50 " + Subject + " \\fs0 \\qc0}")
    file.write(Prepared)

不知道错误在哪里。

原文链接:https://stackoverflow.com//questions/71599756/python-write-command-in-file-does-not-give-output-rtf-file-output

回复

我来回复
  • quamrana的头像
    quamrana 评论

    很明显,您不知道rtf文件是如何格式化的。快速搜索了一下,我发现,也许,大括号是错误的。

    此代码使两段文本在rtf查看器中可见:

    a = r"C:\Users\XYZ/test/abc.rtf"
    Subject = "ABC 123 "
    Prepared = " XYZ 456"
    with open(a, 'w') as file:
        file.write("{\\rtf1 \\qc \\fs50 " + Subject + " \\fs0 \\qc0")
        file.write(Prepared)
        file.write("}")
    
    2年前 0条评论
  • BrainFlooder的头像
    BrainFlooder 评论

    你应该了解 Python 中的 iswmode 是什么。它将完全重写该文件中的内容。如果要在文件中添加内容,请使用a模式(如果没有现有文件,它也会创建一个新文件)。请记住,它不会为您换行,因此如果您想要换行,则需要添加\n

    这段代码应该可以工作。

    a = r"C:/Users/XYZ/test/abc.rtf" # Use / or \, you shouldn't use both
    Subject = "ABC 123 "
    Prepared = " XYZ 456"
    with open(a, 'a') as file:
        file.write("{\\rtf1 \\qc \\fs50 " + Subject + " \\fs0 \\qc0}\n") #Remove the \n if you don't want a new line
        file.write(Prepared)
    
    2年前 0条评论