import os
import re
import shutil
# --------讀寫檔案--------
fpr =
open
('d:\\readtest.txt'
,'r'
)# 開啟讀取檔案
fpw =
open
('d:\\writetest.txt'
,'w+'
)# 開啟寫檔案
readlines = fpr.readlines(
)# 讀取檔案
for readline in readlines:
# 逐行寫入檔案
fpw.write(
str(readline)
)fpw.close(
)# 關閉檔案
# --------遍歷檔案--------
extrafoldername =
['^(before)$'
,'^(old)$'
,'^(debug)$'
,'^(release)$'
,'^(h_ni)$'
,'^(lib_ni)$'
,'^(bk)$'
,'^(backup)$'
,'^(_old)$'
,'^(old)$'
,'^(復件)$'
]extrafilename =
[r'(\.bak)$'
, r'(復件)'
, r'(thumbs.db)'
, r'(\.ncb)$'
, r'(\.opt)$'
, r'(\.plg)$'
, r'(\.suo)$'
, r'(\.ilk)$'
, r'(\.001)$'
, r'(\.002)$'
, r'(\.003)$'
, r'(\.exe1)$'
, r'(\.exe2)$'
, r'(\.exe3)$'
, r'(sequence1)'
, r'(sequence2)'
, r'(sequence3)'
, r'(\.tmp)$'
]for foldername, subfolders, filenames in os.walk(
'd:\\test'):
# 遍歷資料夾
for subfolder in subfolders:
for i in
range
(len
(extrafoldername)):
# 當搜尋到檔名包含extrafoldername中的內容時
if re.
compile
(extrafoldername[i]
, re.ignorecase)
.search(subfolder)
!=none
: shutil.rmtree(os.path.join(foldername +
'\\'
+ subfolder)
)# 刪除該資料夾
break
# 遍歷檔案
for filename in filenames:
for i in
range
(len
(extrafilename)):
# 當搜尋到檔名包含extrafilename中的內容時
if re.
compile
(extrafilename[i]
, re.ignorecase)
.search(filename)
!=none
: os.remove(os.path.join(foldername +
'\\'
+ filename)
)# 刪除該檔案
break
# --------檔案操作--------
os.path.join(
'd:\\'
+'test.txt'
)# 組建路徑
os.remove(
'd:\\test.txt'
)# 刪除檔案
shutil.rmtree(
'd::\\folder'
)# 刪除資料夾
os.path.dirname(os.path.realpath(__file__)
)# 獲取該檔案當前所在目錄
os.makedirs(
'd::\\folder'
)# 建立資料夾
shutil.move(
'd:\\test.txt'
,'d::\\folder'
)#將檔案移動至指定目錄
os.path.exists(
'd::\\folder'
)# false:目錄不存在;true:目錄存在
os.path.isfile(
'd::\\folder'
)# false:不是檔案;true:是檔案
Python常用檔案操作總結
python中對檔案 資料夾的操作需要涉及到os模組和shutil模組。1 建立檔案 os.mknod test.txt 建立空檔案 open test.txt w 直接開啟乙個檔案,如果檔案不存在則建立檔案 2 建立目錄 os.mkdir file 建立目錄 3 複製檔案 shutil.copyf...
python檔案操作總結 python檔案操作總結
python 中os.path模組用於操作檔案或資料夾 os.path.exists path 判斷檔案路徑是否存在 dir c windows if os.path.exists dir print dir exists else print no exists os.path.isfile pa...
Python常用檔案操作
使用python進行檔案操作是各種資料預處理的必備技能。主要涉及的是檔名和路徑字串處理。import os,shutil,sysbase dir os.path.dirname os.path.abspath file 新增到import庫查詢目錄 複製檔案 shutil.copy c a 1.tx...