以下是Python的一个示例代码,可以按字数(字符数)将文本文件拆分成多个文件:
def split_text_file(file_path, max_length):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
chunks = [content[i:i+max_length] for i in range(0, len(content), max_length)]
for i, chunk in enumerate(chunks):
with open(f'{file_path}-{i+1}', 'w', encoding='utf-8') as file:
file.write(chunk)
print(f'文件已拆分成 {len(chunks)} 个文件。')
# 示例用法
split_text_file('example.txt', 1000)
在上述示例中,split_text_file
函数接受两个参数:文件路径 file_path
和最大长度 max_length
。该函数首先打开指定的文本文件,读取文件内容到 content
变量中。
然后,使用列表推导式将文件内容 content
拆分成多个长度为 max_length
的块,存储在 chunks
列表中。
接下来,使用循环遍历 chunks
列表,并将每个块写入一个新的文件中。新文件的命名方式为原文件路径加上索引号,例如 example.txt-1
、example.txt-2
等。
最后,打印出拆分后的文件数量。
你可以根据需要修改 max_length
参数的值来控制每个拆分后文件的最大长度。
上一篇:按子数组中的三个项目排序
下一篇:按子孙节点对数组进行排序