Reputation: 169
Suppose I have a large file name input.txt which contains 10 lines of text:
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
I want to create 5 text files each of which contain 2 lines. Something like this:
./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
... and in continuation.
Can someone please help me out?
Upvotes: 2
Views: 221
Reputation: 54148
A generix way would be
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])
Upvotes: 1
Reputation: 169
Here is the script:
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
Upvotes: 1