如何使用python从一个大的文本文件创建5个小的文本文件



假设我有一个大文件名input.txt,其中包含10行文本:

Lorem Ipsum is simply a dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s  when an unknown printer took a galley of type and
scrambled it to make a type  specimen book. It has survived not only
five centuries, but also the leap into  electronic typesetting,
remaining essentially unchanged. It was popularised in  the 1960s with
the release of Letraset sheets containing Lorem Ipsum passages,  and
more recently with desktop publishing software like Aldus PageMaker
including  versions of Lorem Ipsum. Contrary to popular belief, Lorem
Ipsum is not simply  random text. It has roots in a piece of classical

我想创建5个文本文件,每个文件包含2行。类似这样的东西:

./first.txt
Lorem Ipsum is simply a dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
./second.txt
since the 1500s  when an unknown printer took a galley of type and
scrambled it to make a type  specimen book. It has survived not only

以及继续。

有人能帮帮我吗?

这是脚本:

file = open('input.txt', 'r', encoding="utf-8")
Lines = file.readlines()  
count = 0
i = 0
string = []
for line in Lines:
#     print(line)
if(count == 2):
write_file = open(str('input') + str(i) + '.txt', 'w', encoding="utf-8")
write_file.writelines(string)
string = []
i += 1
count = 0
else:
string.append(line)
count += 1

是一种通用方法

with open('input.txt', 'r', encoding="utf-8") as fic:
lines = fic.readlines()
# number of lines per file
split_size = 2
for idx in range(len(lines) // split_size):
with open(f"input{idx}.txt", 'w', encoding="utf-8") as fic:
fic.writelines(lines[idx * split_size:(idx + 1) * split_size])

最新更新