repeating json file modifications for multiple files

Viewed 13

I wanted to read files from test-00000-of-00016, test-00001-of-00016 to test-00015-of-00016 and modify them and then write new files like

   import json 
    with open('test-00000-of-00016.txt') as f, open('file-00000-of-00016.txt', 'w') as target:
        for line in f:
            l = json.loads(line)
            l['utterance'] = l['utterance'].replace('play ', '', 1)
            target.write(json.dumps(l))

How do I open and write files in sequence to do that instead of doing this manually?

1 Answers

Just use an f-string with the numerals that are set to increase being formated by a for i in range loop. That will update the path string on each iteration. Then do the same thing you were doing before within the loop.

import json

for i in range(16):
    path = f'test-000{i:02d}-of-00016.txt'
    content = open(path).read()
    with open(path, "w") as target:
        for line in content.split("\n"):
            l = json.loads(line)
            l['utterance'] = l['utterance'].replace('play ', '', 1)
            target.write(json.dumps(l))
Related