How to apply a script to all files in extension and change names accordingly?

Question:

I have a script which does a certain transformation to a file.

pipeline.load_files('txt', '1.txt')
pipeline.transform('function0','file.jpg', '1.txt')
pipeline.write('txt', 'result.txt', opt={'c':None})
pipeline.score(function='function1', file ='file.jpg')
pipeline.score(function='function2', file ='file.jpg')
pipeline.write_csv('result.csv')

Now I want to use this script for all 100 txt files (1.txt-100.txt) in my folder. So in the end I should have 100 files named ‘result1.csv’…’result100.csv’ and ‘result1.txt’….’result100.txt’. How can I do this? I know it has to be a for cycle loop, but I’m not sure how to change filenames.

Asked By: lemontree

||

Answers:

Use formatted strings

import glob, os

os.chdir("PUT.YOUR.DIRECTORY.CONTAINING.TEXT.FILES.HERE")
for i, file in enumerate(glob.glob("*.txt")):
    ...
    pipeline.load_files('txt', file)
    ...
    pipeline.write('txt', f'result{i+1}.txt', opt={'c':None})
    ...
    pipeline.write_csv(f'result{i+1}.csv')
Answered By: Himanshuman