Search code examples
pythonioreadfilewritefile

Python - Read Multiple Files & Write To Multiple New Files


I know there's a lot of content about reading & writing out there, but I'm still not quite finding what I need specifically.

I have 5 files (i.e. in1.txt, in2.txt, in3.txt....), and I want to open/read, run the data through a function I have, and then output the new returned value to corresponding new files (i.e. out1.txt, out2.txt, out3.txt....)

I want to do this in one program run. I'm not sure how to write the loop to process all the numbered files in one run.


Solution

  • If you want them to be processed serially, you can use a for loop as follows:

    inpPrefix = "in"
    outPrefix = "out"
    for i in range(1, 6):
        inFile = inPrefix + str(i) + ".txt"
        with open(inFile, 'r') as f:
            fileLines = f.readlines()
    
        # process content of each file
        processedOutput = process(fileLines)
    
        #write to file
        outFile = outPrefix + str(i) + ".txt"
        with open(outFile, 'w') as f:
             f.write(processedOutput)
    

    Note: This assumes that the input and output files are in the same directory as the script is in.