Python3自動化_文件批量處理(文本、PDF、Excel;讀取、篩選、導出)


利用Python3腳本語言的簡練語法,高級語言的豐富類庫,快速寫了幾個文件讀取、篩選、導出的“腳本”。

這里簡單總結一下關鍵功能。

 讀取ini配置文件

檢查ini文件是否存在;檢查輸入的key在ini文件里是否有定義。

 1 import configparser 
2
4 def getConfigInfo(_ini_nm): 5 6 # Open Ini File 7 config = configparser.ConfigParser() 8 if not config.read(os.path.join(os.getcwd(), _ini_nm + r'.ini')): 9 printLog('E', 'Read Ini file fail.') 10 11 while True: 12 sysCode = input(r'Please input the system code : (Press [Enter] to quit):').strip() 13 if 0 == len(sysCode.strip()): 14 exit() 15 16 # Init ConnectionSettings 17 if sysCode in config.sections(): 18 return dict(config[sysCode]) 19 else: 20 print('Ini info of System [%s] is blank.\n' % sysCode)

 

多參數輸入的獲取

檢查參數個數;檢查參數合法性(長度,是否目錄);檢查參數是否整個都是漢字。

 1 def _main():
 2 
 3     path = ''
 4     keyWord = ''
 5 
 6     while True:
 7         para = input(r'Please input the PDF directory and Key Word: (Press [Enter] to quit):').strip().split()
 8 
 9         if 0 == len(para):
10             exit()
11 
12         if 2 != len(para):
13             print('Two para -> [PDF directory and Key Word] is needed .' + '\n')
14             continue
15 
16         path = para[0]
17         keyWord = para[1]
18 
19         if not os.path.exists(path):
20             print('input path is not a exists path.' + '\n')
21             continue
22 
23         flg = True
24         for char in keyWord.strip():
25             if char <= u'\u4e00' or char >= u'\u9fa5':
26                 flg = False
27                 break
28         if not flg:
29             print('Please input the Chinese Key Word for search.(Such as \'物流\').' + '\n')
30             continue
31 
32         break

 

PostgreSQL數據庫處理

根據ini文件定義的數據庫連接信息,嘗試連庫;執行SQL文。

 1 import psycopg2 
4
import traceback 5 6 def connDB(_cfg): 7 try: 8 conn = psycopg2.connect(database=_cfg['servicename'], 9 user=_cfg['dbuser'], 10 password=_cfg['dbpw'], 11 host=_cfg['host'], 12 port=_cfg['port']) 13 return conn 14 except Exception: 15 printLog('E', 'Exception occur at DB Connection.' + '\n' + traceback.format_exc()) 16 17 def executeSql(_cfg, _sql): 18 try: 19 conn = connDB(_cfg) 20 cur = conn.cursor() 21 cur.execute(_sql) 22 23 results = cur.fetchall() 24 return list(map(lambda x: x[0], results)) 25 except Exception: 26 printLog('E', 'Exception occur at Execute SQL.' + '\n' + traceback.format_exc()) 27 finally: 28 cur.close() 29 conn.rollback() 30 conn.close()

  

日志處理

定義輸出日志的級別;異常級別時,處理結束。

 1 logging.basicConfig(filename='log_' + datetime.now().strftime('%Y%m%d') + '.txt',
 2                     level=logging.INFO,
 3                     format=' %(asctime)s - %(levelname)s - %(message)s')
 4 
 5 logLevel = {'D': logging.DEBUG,
 6             'I': logging.INFO,
 7             'W': logging.WARNING,
 8             'E': logging.ERROR,
 9             'C': logging.CRITICAL}
10 
11 def printLog(_lvl, _msg):
12     logging.log(logLevel[_lvl], _msg)
13     if logging.ERROR == logLevel[_lvl]:
14         print(_msg)
15         exit()
16 
17 
18 printLog('E', 'srcpath is not a exists path.')
19 printLog('I', 'Get Src Path : %s' % srcPath)

  

MAP函數運用

列表元素批量處理,按第二個下划線字符截取字符串。

1 def getPreOfNm(x):
2     if 1 < x.count('_'):
3         return x[0:x.find('_', x.find('_') + 1)]
4     else:
5         return x
6 
7 # Get prefix of CRUD object name
8 prefixObjNm = list(set(map(getPreOfNm, lstTb)))
9 prefixObjNm.sort()

  

目錄處理

目錄/文件判斷;目錄的路徑分割;完整路徑的文件名取得;

 1 # Check the srcPath
 2 fullFilePaths = []
 3 if os.path.isdir(srcPath):
 4     for folderName, subFolders, fileNames in os.walk(srcPath):
 5         if os.path.split(folderName)[1] in ['tcs', 'doc']: continue
 6         for fn in fileNames:
 7             # Get src file
 8             mObj = fileNmReg.search(fn)
 9             if mObj:
10                 fullFilePaths.append(os.path.join(folderName, fn))
11 elif os.path.isfile(srcPath):
12     # Get src file
13     fn = os.path.basename(os.path.realpath(srcPath))
14     mObj = fileNmReg.search(fn)
15     if mObj:
16         fullFilePaths.append(srcPath)

  

PDF文件讀取

來源:https://www.cnblogs.com/alexzhang92/p/11488949.html

 1 from pdfminer.converter import TextConverter
 2 from pdfminer.layout import LAParams
 3 from pdfminer.pdfinterp import PDFResourceManager, process_pdf
 4 import os
 5 
 6 
 7 def read_pdf(pdf):
 8     # resource manager
 9     rsrcmgr = PDFResourceManager()
10     retstr = StringIO()
11     laparams = LAParams()
12     # device
13     device = TextConverter(rsrcmgr, retstr, laparams=laparams)
14     process_pdf(rsrcmgr, device, pdf)
15     device.close()
16     content = retstr.getvalue()
17     retstr.close()
18     # 獲取所有行
19     contents = str(content).split("\n")
20 
21     return contents

 

CSV文件導出

1 # Init result file
2 rstFile = open(os.path.join(srcPath, '[CRUD]' + datetime.now().strftime('%Y%m%d%H%M%S') + '.csv'), 'w', newline='')
3 rstWtr = csv.writer(rstFile, delimiter='\t', lineterminator='\n')
4 # Write head
5 rstWtr.writerow(['TYPE', 'CI', 'ENCODE', 'LINE NUM', 'CRUD', 'TABLE NM', 'FULL PATH'])

 

Excel文件讀寫

利用openpyxl讀寫xlsx,不支持xls;

獲取工作簿、工作表、單元格(直接定位及相對位置);

單元格賦值。

 1 import os, openpyxl
 2 
 3 # Init file path
 4 srcPath = r'.\newDocs'
 5 
 6 # Start Search
 7 for folderName, subFolders, fileNames in os.walk(srcPath):
 8 
 9     for fileName in fileNames:
10 
11         filePath = os.path.join(folderName, fileName)
12 
13         try:
14             wb_WorkBook = openpyxl.load_workbook(filePath)
15         except openpyxl.utils.exceptions.InvalidFileException:
16             print(fileName + '\t' + 'xls read failed')
17             wb_WorkBook.close()
18             continue
19 
20         # _履歴
21         st_Rireki = wb_WorkBook['_履歴']
22         if None is st_Rireki:
23             print(fileName + '\t' + '_履歴 is not exist')
24             continue
25 
26         cl_Version = st_Rireki['AQ10']
27         while True:
28             if None is cl_Version.value or \
29                0 == len(str(cl_Version.value).strip()):
30                 cl_Version.value = '1.0.2.0'
31 
32                 cl_JobNo = st_Rireki.cell(row=cl_Version.row - 1, column=cl_Version.column)
33                 cl_JobNo.value = '123'
34  
35                 wb_WorkBook.save(filePath)
36 
37                 break
38 
39             else:
40                 cl_Version = st_Rireki.cell(row=cl_Version.row + 5, column=cl_Version.column)
41 
42         wb_WorkBook.close()

 

 

轉載請注明原文鏈接,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM