[英]Python - Read files from folder and Write files to different folder
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读取文件夹中的文件列表,检查每个文件每行的第 7 列是否不等于'*',然后必须将这些行写入 output 文件夹中的每个文件
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: Output 在终端:
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:文件夹中文件的实际 output:
This PC > Desktop > TempCOBOL > Updated这台电脑 > 桌面 > TempCOBOL > 更新
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.问题:脚本执行并读取文件夹中的 2 个 CBL 文件,并在 output 文件夹中创建了 2 个 CBL 文件。 The output CBL files to have 1) ABCDEFGH.CBL - 187 lines and 2) IJKLMNOP.CBL - 182 lines
output CBL 文件具有 1) ABCDEFGH.CBL - 187 行和 2) IJKLMNOP.CBL - 182 行
However, the actual output lines in但是,实际的 output 行在
1) ABCDEFGH.CBL - 1 line
030100 MASTER-CAT. 04050000
2) IJKLMNOP.CBL - 1 line
030100 MASTER-CAT. 04050000
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因为 w 用最后一行擦除现有文件,所以每个新行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.