可以使用Python的pandas和pyth工具包来处理RTF文件和CSV文件的读写,以下是示例代码:
import os
import pandas as pd
import pyth.plugins.rtf15.reader
from pyth.plugins.plaintext.writer import PlaintextWriter
rtf_folder = "/path/to/rtf/folder"
csv_file = "/path/to/csv/file.csv"
# 获取文件夹中的所有RTF文件名
rtf_files = [f for f in os.listdir(rtf_folder) if f.endswith('.rtf')]
# 循环处理每个RTF文件
rows = []
for rtf_file in rtf_files:
# 读取RTF文件并转换成纯文本格式
rtf_path = os.path.join(rtf_folder, rtf_file)
with open(rtf_path, "r") as rtf_file:
rtf_content = rtf_file.read()
rtf_doc = pyth.plugins.rtf15.reader.read(rtf_content)
plaintext_writer = PlaintextWriter()
plain_text = plaintext_writer.write(rtf_doc).getvalue()
# 将文件名和文本内容存储到一行数据中
row = {'filename': rtf_file, 'content': plain_text}
rows.append(row)
# 将所有行数据装载到pandas的DataFrame中,并将DataFrame的数据保存到CSV文件中
df = pd.DataFrame(rows)
df.to_csv(csv_file, index=False)
运行以上代码,将会读取RTF文件夹中的所有RTF文件,将每个文件的文件名和内容存储到DataFrame中,并将DataFrame的数据写入到CSV文件中。生成的CSV文件将包括两列数据:文件名和RTF文件中的文本内容。