Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

io - 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.

question from:https://stackoverflow.com/questions/65859367/python-read-multiple-files-write-to-multiple-new-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...