0

... and decide execution of that block based on the presence of that word?

For example I have this:

for frame in range(10):
    with open('frame_init.gro', 'w') as g:
        # do something
    with open('frame_next.gro', 'w') as h:
        # do something

When "frame" reaches 9, I don't want the whole with open('frame_next.gro', 'w') as h block to execute at all. Of course I have considered just encasing it in a if frame != 9 but my actual entire code is really long so it would be nice if I could just scan my script within the script itself if it is possible.

For those curious about what other things frame_next.gro is involved in, the answer is lots of calculations

sneedshelp
  • 13
  • 6
  • This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you explain what problem you are trying to solve with it? – Klaus D. Nov 12 '18 at 05:05
  • wow, this is actually really condescending. Thanks a lot. – sneedshelp Nov 12 '18 at 09:56

1 Answers1

0

You can do something like this:

a = 0
b = 1
print a + b

with open(__file__, 'r') as f:
    lines = f.read().split('\n')
    val = int(lines[0].split(' = ')[-1])
    new_line = 'a = {}'.format(val+1)
    new_file = '\n'.join([new_line] + lines[1:])

with open(__file__, 'w') as f:
    f.write('\n'.join([new_line] + lines[1:]))

From here: How can I make a python script change itself?

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46