Home > OS >  write specific content of a large file to multiple new file
write specific content of a large file to multiple new file

Time:11-11

I have a large txt file in format:

bbox_003266.txt
172.56 96.36 199.61 295.15
922.0 79.9 1242.0 349.52
378.56 128.58 803.91 234.82
701.14 176.7 862.34 285.47
bbox_003200.txt
705.95 117.81 1242.0 252.43
1036.12 183.52 1242.0 375.0
124.11 143.43 296.91 230.32
0.0 6.6 112.99 375.0
0.0 186.66 14.82 375.0

for each line beginning with bbox, I want to write the content below that to a new file with the same name as the bbox. i.e in file above, I want to have two files with names: bbox_003266.txt and bbox_003200.txt. I have tried this:

file_in = 'final.txt'

counter = 3199 

with open(file_in, 'r') as fin:    
line = fin.readline() # read file in line by line
while line: 
    if 'bbox' in line:
        
        try:
            fout.close() # close the old file
        except:
            pass
        # augment the counter and open a new file
        counter  = 1 
        fout = open('' % counter, 'w')
    fout.write(line) # write the line to the output file
    line = fin.readline() # read the next line of the input file
fout.close() # close the last output file

CodePudding user response:

Your approach is right, just fixed some logical bugs and your code is working fine

file_in = 'final.txt'

fout = None

with open(file_in, 'r') as fin:    
    line = fin.readline() # read file in line by line
    while line: 
        if 'bbox' in line:
            try:
                if fout is not None:
                    fout.close() # close the old file
            except:
                pass

            fout = open(line.strip(), 'w')
            print('New file created', line.strip())
        else:
            fout.write(line) # write the line to the output file
        
        line = fin.readline() # read the next line of the input file

fout.close() # close the last output file
  • Related