[英]Python - Read files from folder and Write files to different 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 在終端:
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
文件夾中文件的實際 output:
這台電腦 > 桌面 > TempCOBOL > 更新
Name Date Modified Type Size
ABCDEFGH.CBL 9/8/2022 time CBL file 1KB
IJKLMNOP.CBL 9/8/2022 time CBL file 1KB
問題:腳本執行並讀取文件夾中的 2 個 CBL 文件,並在 output 文件夾中創建了 2 個 CBL 文件。 output CBL 文件具有 1) ABCDEFGH.CBL - 187 行和 2) IJKLMNOP.CBL - 182 行
但是,實際的 output 行在
1) ABCDEFGH.CBL - 1 line
030100 MASTER-CAT. 04050000
2) IJKLMNOP.CBL - 1 line
030100 MASTER-CAT. 04050000
嘗試更換:
os.path.basename(inpfile)) , 'w')
經過
os.path.basename(inpfile)) , 'a')
因為 w 用最后一行擦除現有文件,所以每個新行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.