python批量處理檔案/操作檔案
阿新 • • 發佈:2019-02-20
Python批量處理/操作檔案
python自動化處理檔案非常實用,尤其是在大量重複勞動中
本文以批量處理不同資料夾下的文字檔案為例:
os模組
檔案路徑狀態:
E:\CSDN
………….\demo1
……………………\demo1dir
……………………\demo11.txt
……………………\demo12.txt
……………………\demo13.txt
………….\demo2
……………………\demo2dir
……………………\demo21.txt
……………………\demo22.txt
……………………\demo23.txt
………….\demo3
……………………\demo3dir
……………………\demo31.txt
……………………\demo32.txt
……………………\demo33.txt
………….\demo.txt
@python
import os
PATH = r'E:\CSDN'
for elem in os.walk(PATH):
print(elem)
('E:\\CSDN', ['demo1', 'demo2', 'demo3'], ['demo.txt'])
('E:\\CSDN\\demo1', ['demo1dir'], ['demo11.txt', 'demo12.txt', 'demo13.txt'])
('E:\\CSDN\\demo1\\demo1dir', [], [])
('E:\\CSDN\\demo2', ['demo2dir'], ['demo21.txt', 'demo22.txt', 'demo23.txt'] )
('E:\\CSDN\\demo2\\demo2dir', [], [])
('E:\\CSDN\\demo3', ['demo3dir'], ['demo31.txt', 'demo32.txt', 'demo33.txt'])
('E:\\CSDN\\demo3\\demo3dir', [], [])
不難發現,os.walk從指定目錄(資料夾)一直往下讀取
對每個目錄檔案(資料夾)進行返回
即:每個elem代表一個資料夾
elem[0] 第一個元素為路徑名
elem[1] 第二個元素為該路徑下的所有資料夾名
elem[2] 第三個元素為該路徑下的所有檔案(非資料夾)
舉例:
- 如果需要所有的txt,則如下:
@python
import os
PATH = r'E:\CSDN'
for elem in os.walk(PATH):
if len(elem[2]) > 0:
print(elem[2])
['demo.txt']
['demo11.txt', 'demo12.txt', 'demo13.txt']
['demo21.txt', 'demo22.txt', 'demo23.txt']
['demo31.txt', 'demo32.txt', 'demo33.txt']
- 如果需要輸出每個txt檔案的絕對路徑,則如下:
@python
import os
PATH = r'E:\CSDN'
for elem in os.walk(PATH):
if len(elem[2]) > 0:
for f in elem[2]:
print(elem[0] + '\\' + f)
E:\CSDN\demo.txt
E:\CSDN\demo1\demo11.txt
E:\CSDN\demo1\demo12.txt
E:\CSDN\demo1\demo13.txt
E:\CSDN\demo2\demo21.txt
E:\CSDN\demo2\demo22.txt
E:\CSDN\demo2\demo23.txt
E:\CSDN\demo3\demo31.txt
E:\CSDN\demo3\demo32.txt
E:\CSDN\demo3\demo33.txt