Home > OS >  Split text file to multiple files by specific string or line number using python
Split text file to multiple files by specific string or line number using python

Time:06-29

Want to split text file based on specific text(string) but unable to find solution so first collect line number of in which that string is existed and try to split file.

here is the code for collecting lines form text file.

file1 = open("textfile_1.txt", "r")

string1 = 'Weight Total'

flag = 0
index = 0
fl = 1

Spl_Lines = []
for line in file1:  
    index  = 1 

    if string1 in line:
        Spl_Lines.append(index)
print(Spl_Lines)

As result getting line numbers in which "Weight Total" is mentioned.

Out put: [350, 850, 1123, 1640, 1810, 2250]

Now want to split the text file from the listed lines so I tried below code but it didn't work. struggling to split text file with the specific word string matching.

lines = file1.readlines()
# print(lines) getting blank
for i in Spl_Lines:
    with open('E' str(fl) ".txt",'w') as file:
        for line in lines[i]:
            file.write(line)
        fl  = 1

I tried this but not working, how to split a text file into multiple files by specific string or listed lines.

CodePudding user response:

Why don't you split the string on your string1, and then append the text back?

file1 = open("textfile_1.txt", "r")
string1 = 'Weight Total'
text = file1.read()

text_splitted = [i   string1 for i in text.split(string1)]

CodePudding user response:

This can be done in a single pass of the input file as follows:

key = 'Weight Total'

outfile = None
fileno = 0

with open('textfile_1.txt') as infile:
    while line := infile.readline():
        if outfile is None:
            fileno  = 1
            outfile = open(f'E{fileno}.txt', 'w')
        outfile.write(line)
        if key in line:
            outfile = outfile.close()
if outfile:
    outfile.close()

Note:

This assumes that any line containing the key is to be included in the output file(s)

  • Related