以下是一个示例代码,演示了如何按关键字拆分文件:
def split_file_by_keyword(file_path, keyword):
with open(file_path, 'r') as file:
content = file.read()
# 按关键字拆分内容
sections = content.split(keyword)
# 生成拆分后的文件
for i, section in enumerate(sections):
filename = f'{file_path}_{i+1}.txt'
with open(filename, 'w') as file:
file.write(section)
print(f'Section {i+1} saved as {filename}')
使用示例:
file_path = 'example.txt' # 文件路径
keyword = '###' # 关键字
split_file_by_keyword(file_path, keyword)
这段代码首先打开指定文件,并将其内容读取到一个变量中。然后,使用关键字对内容进行拆分,将拆分后的各个部分存储到一个列表中。接下来,循环遍历列表中的每个部分,将其分别写入以原文件名加后缀编号的文件中。最后,打印出每个部分的保存文件名。
假设example.txt
的内容如下:
This is section 1.###
This is section 2.###
This is section 3.
运行以上示例代码后,将会生成三个新的文件:example.txt_1.txt
、example.txt_2.txt
和example.txt_3.txt
。其中,example.txt_1.txt
的内容为This is section 1.
,example.txt_2.txt
的内容为This is section 2.
,example.txt_3.txt
的内容为This is section 3.
。
上一篇:按关键性对数组进行排序