Sophi
Sophi

Reputation: 15

How to write each part of a file in a seperate directory?

I have a file (name:state2) with the following structure:

timestep
  0.0000000      0.0000000      0.0000000
  0.0000000      0.0000000      1.2176673
timestep
 -0.0151405     -0.0000000     -0.0874954
 -0.0347223      0.0000001      1.2559323
timestep
 -0.0492274      0.0000001     -0.1238961
 -0.0976473     -0.0000002      1.2335932
.... (24 timesteps)

I am trying to put each timestep (only numbers) in a separate file within a directory. I have written the following code but it only writes the first timestep data into a file. If I remove the break, then it will write the whole original file again into separate files.

import os

steps = []
BaseDir=os.getcwd()
data=os.path.join(BaseDir, 'state2')
f= open(data, 'r')
all_lines = f.readlines()
for k in range(24):
    path = os.path.join(BaseDir, 'steps_{0:01d}'.format(k))
    os.mkdir(path)
    dest = os.path.join(BaseDir,'steps_{0:01d}'.format(k), 'step{0:01d}'.format(k))
    fout = open(dest, 'w')
    for i in range(0, len(all_lines)):
        if 'timestep' in all_lines[i]:
           fout.write('{0}{1}}'.format(all_lines[i+1], all_lines[i+2]))
           break

Upvotes: 0

Views: 44

Answers (1)

pho
pho

Reputation: 25489

You don't need the nested for with the if and break shenanigans. All you need to do is:

  • Iterate through the lines in your original file.
    1. When you see "timestep", open a new file to write in and move on to the next line.
    2. If you don't see "timestep", write the line to the current file and move on to the next line.
fout = None
timestepnum = 0
for line in all_lines:
    if line == "timestep": # Or whatever condition you identify
        # this line says timestep, so we have now started looking at a new timestep (condition 1)
        if fout is not None:
           fout.close() # close the old timestep's file if it is already open
        
        timestepnum += 1

        # make the directory
        path = os.path.join(BaseDir, 'steps_{0:01d}'.format(timestepnum))
        os.mkdir(path)

        # open the file
        filename = os.path.join(BaseDir, f"steps_{timestepnum:01d}", f"step{timestepnum:01d}") # Code to specify file name
        fout = open(filename, 'w')

    elif fout is not None:
        # Condition 2 -- write this line as-is to the file.
        fout.write(line)

Upvotes: 1

Related Questions