0

I have a speck file (can be editted like a txt) of the format

datavar 0 pictype
datavar 1 absmag

texturevar pictype

#The texture filename to associate with txnum 1
texture -a 24 24_rot_0001.sgi

#x       y       z       no.   lum
100.0   100.0   100.0   24     10.0

What I need to do is to create "n" number of files, each named rot_"n".speck with the the only change within the file being the rot_0001.sgi being changed to rot_00"n".sgi. I am aware that probably quite a simple python loop can perform this. But I do not know the form it would take. Can you help?

1 Answers1

0

You are right you can use a FOR loop to accomplish this. I used the following code to write 4 files named rot_n.spek. I used the file you presented above to create the files.

import re

for j in range(4):
    file_name = "rot_{:04d}.spek".format(j)
    with open(file_name, 'w+') as new_file:
        with open('simple.txt', 'r') as old_file:
                for line in old_file:
                    new_file.write(re.sub(r"24_rot_\d+.sgi",
                    "24_rot_00{:04d}.sgi".format(j), line ) )

If because you are always reading in the same file each time you could also use string replace.

new_file.write(line.replace("24_rot_0001.sgi", "24_rot_{:04d}.sgi".format(j)))

I found this SO answer helpful.

lwileczek
  • 2,084
  • 18
  • 27
  • 1
    I'd use `"rot_{:04d}.spek".format(j)` and `new_file.write(re.sub(r"24_rot_\d+.sgi", "24_rot_{:04d}.format(j), line))`. You could also open the input file just once, and either rewind it every time you write a new file, or just read it once as a whole. – Jan Christoph Terasa Jul 02 '18 at 16:17