Python - Read files from folder and Write files to different folder

Viewed 35

Read list of files in Folder, check if 7th column in every line of each file not equal to '*', then have to write those lines to each file in output folder

from pathlib import Path
import sys
import glob
import os

input_dir = Path('C:\\Users\\user1\\Desktop\\Cobol/')

inpfiles = input_dir.glob('*.CBL')

#Process files for writing uncommented lines
def process_files_uncomment(inpfiles):
    global writereccount
    for inpfile in inpfiles:
        writereccount = 0
        try:
            inpfile_handle = open(inpfile, 'r')
            line = inpfile_handle.readlines()
            for i in line:
                if i[0] == '\t':       #Condition to check if line starts with tab
                    pass
                elif i[6] != '*':      #Condition to check 6th column of line
                    writereccount += 1
                    f=open(os.path.join('C:\\Users\\user1\\Desktop\\TempCOBOL\\Updated',
                    os.path.basename(inpfile)) , 'w')
                    f.write(i)
                    #
                else:
                    pass
            
            print('Total number of UN-COMMENTED LINES           :', writereccount)                
        except:
            print('Exception while Reading File')

process_files_uncomment(inpfiles)

Output in Terminal:

PS C:\Users\user1\Python-1> & C:/Users/user1/AppData/Local/Programs/Python/Python310/python.exe c:/Users/user1/Python-1/process_files_writeuncomment.py
Total number of UN-COMMENTED LINES           : 187
Total number of UN-COMMENTED LINES           : 182

Actual output of files in Folder:

This PC > Desktop > TempCOBOL > Updated

    Name                   Date Modified              Type                 Size
    ABCDEFGH.CBL           9/8/2022 time              CBL file             1KB
    IJKLMNOP.CBL           9/8/2022 time              CBL file             1KB

Problem: Script executed and Read 2 CBL files in the Folder, and created 2 CBL files in output folder. The output CBL files to have 1) ABCDEFGH.CBL - 187 lines and 2) IJKLMNOP.CBL - 182 lines

However, the actual output lines in

1) ABCDEFGH.CBL - 1 line

               030100           MASTER-CAT.                                            04050000

2) IJKLMNOP.CBL - 1 line

               030100           MASTER-CAT.                                            04050000
1 Answers

try replacing :

os.path.basename(inpfile)) , 'w')

by

os.path.basename(inpfile)) , 'a')

because w erase the existing file with last line, every new line

Related