python) split txt file To save as multiple files

Asked 2 years ago, Updated 2 years ago, 75 views

How to load a txt file, divide the sentence, and save it as multiple txt files

For example, if there are 10 sentences in the txt file and you want to divide them into 2 or 3 files,

If you divide 10 sentences into 2 sentences, 5 lines each document_1 document_2.txt

Divided into three, 3, 3, and 4 lines each, Document_1 Document_2 Document_3.txt

def split_txt(num_of_file):

file =open('sample.txt', 'w')

line = file.readline()

line_size = len(line) // num_of_files

for i in range(0, len(line), line_size): 

Is there a way to use it?

python txt

2022-09-20 17:54

1 Answers

with open('t.text', 'r') as txt:
    a = txt.readlines()
for i in range(len(a)):
    b = i + 1
    with open(f't-{b}.text', 'w+') as txt:
        txt.write(a[i])

I think this will work.


2022-09-20 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.