如何使用Python创建、编辑或转换.rtf文件?实操问题求助
Hey there! Let's break down why your original RTF code failed, then walk through easy ways to convert TXT to valid RTF files.
First, the problems with your initial code:
- You didn’t wrap your filename in quotes:
myfile.rtfshould be"myfile.rtf"(Python treats unquoted names as variables, which will throw an error) - RTF has special characters (
{,},\) that break the file structure if left unescaped. Ifmy_String_hereincludes any of these, your RTF will be invalid.
Here are three straightforward solutions:
1. Fix Your Manual RTF Generation Code
If you want to stick with writing RTF directly, add a simple escape function to handle special characters and fix the filename issue:
def escape_rtf_text(text): # Escape RTF-specific characters and handle line breaks escape_map = { '\\': '\\\\', '{': '\\{', '}': '\\}', '\n': '\\par\n' } for char, replacement in escape_map.items(): text = text.replace(char, replacement) return text # Example usage output_file = "my_valid_rtf.rtf" my_text = "Hey! This has {curly brackets} and a \\backslash." # Use 'w' mode to overwrite instead of 'a' (avoids duplicate RTF headers) with open(output_file, 'w') as f: f.write("{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard\n") f.write(escape_rtf_text(my_text)) f.write("\n\par}")
Using 'w' instead of 'a' ensures you don’t stack multiple RTF headers if you run the code multiple times, which would make the file invalid.
2. Use a Python Library (No Manual RTF Headaches)
For a more robust, low-effort solution, use a dedicated RTF library like python-rtf (install it first with pip install python-rtf). It handles all formatting and escaping automatically:
from rtf import RTFDocument, Paragraph output_file = "my_valid_rtf.rtf" my_text = "Hey! This has {curly brackets} and a \\backslash." doc = RTFDocument() doc.add(Paragraph(my_text)) with open(output_file, 'w') as f: doc.write(f)
This is also great if you want to add formatting like bold or italics later—just use the library’s built-in methods.
3. Quick Non-Code Conversion (For One-Off Tasks)
If you don’t need to automate this, your OS has built-in tools:
- Windows: Open the TXT file in Notepad, copy its contents into Word, then save the document as RTF.
- Mac: Open the TXT file in TextEdit, go to
File > Export, then selectRich Text Format (.rtf)as the output format.
内容的提问来源于stack exchange,提问作者Python account

