python遍歷檔案 和如何刪除某個檔案

2021-07-14 10:53:22 字數 1591 閱讀 5596

(1)遍歷指定路徑的檔案

import os

allfile=

def dirlist(path):

filelist=os.listdir(path)#列出當前的目錄的檔案

for filename in filelist:

if filename=="system volume information":#遮蔽system volume information 檔案,因為該檔案為系統檔案沒有許可權讀取會出錯

continue

filepath=os.path.join(path,filename) #把檔名與路徑連線,形成完整的絕對路徑

if os.path.isdir(filepath): #判斷是否是資料夾,是則繼續開啟

dirlist(filepath) #是資料夾繼續開啟

return allfile

dirlist("e:") #遍歷e盤下的檔案

for a in allfile:

print a

(2)刪除指定路徑的檔案

import os

import shutil

def delnofile(path,name):#刪除空資料夾用該函式

filelist=os.listdir(path)

for filename in filelist:

filepath=os.path.join(path,filename)

if filename==name:

try:

os.rmdir(filepath)

print '成功刪除了在%s下的資料夾%s'%(filepath,name)

except:

print '刪除出錯,在%s下的資料夾%s非空無法刪除'%(filepath,name)

if os.path.isdir(filepath):

delnofile(filepath,name)

delnofile("c:\\users\\lai\\desktop\\test",'b')

def delfile(path,name):#刪除非空資料夾用該函式

filelist=os.listdir(path)

for filename in filelist:

filepath=os.path.join(path,filename)

if filename==name:

try:

shutil.rmtree(filepath)

print '成功刪除了在%s下的資料夾%s'%(filepath,name)

except:

print '刪除出錯,在%s下的資料夾%s無法刪除'%(filepath,name)

if os.path.isdir(filepath):

delfile(filepath,name)

delfile("c:\\users\\lai\\desktop\\test",'b')

Python 如何刪除檔案或資料夾?

在本教程中,我們將學習如何在python刪除檔案或目錄。使用os模組,在python中刪除檔案或資料夾的過程非常簡單。首先,我們將看到使用os.remove從目錄中刪除檔案的方法 usr bin python import os getting the filename from the user ...

python 檔案遍歷

1.使用os.listdir dir 得到一定list包含了目錄下所有的檔案和資料夾 os.path.join dir,filename 獲得檔案的全路徑 os.path.isdir filepath 判斷是不是乙個dir import os,sys import re def deal log l...

Python檔案遍歷

python檔案遍歷 重點 以下兩個方法裡面的path都是絕對路徑。os.path.isdir path os.path.isfile path 深度遍歷檔案 如下 借用棧的後進先出的思想實現給定path下檔案的遍歷 import os 新建乙個列表 stack def getalldirdep p...