1. 程式人生 > >python實現文件夾遍歷

python實現文件夾遍歷

問題 dirname 元組 一個 操作 目錄下的文件 exist exists lena

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(path) 判斷path是否是文件

dir = "c:\windows\system32\cmd.exe"
if os.path.isfile(dir) :
  print "file exists"
else :
  print "no exists"

os.path.getsize(path) 獲取path文件的大小

size = os.path.getsize(dir)
print size/1024

os.path.walk(path) 遍歷path,返回一個三元組(dirpath, dirnames, filenames). dirpath表示遍歷到的路徑, dirnames表示該路徑下的子目錄名,是一個列表, filesnames表示該路徑下的文件名,也是一個列表. 例如: 當遍歷到c:\windows時,dirpath="c:\windows", dirnames是這個路徑下所有子目錄名的列表,dirnames是這個路徑下所有文件名的列表

for (root, dirs, files) in os.walk("C:\windows"): 列出windows目錄下的所有文件和文件名
  for filename in files:
    print os.path.join(root,filename)

  for dirc in dirs:

    print os.path.join(root,dirc)

問題 1 獲取給定文件夾的大小?

  要遍歷文件的大小,只需要遍歷文件內的所有文件,然後將所有文件夾的大小加起來

def getDirSzie(dir) :
for (root,dirs,files) in os.walk(dir,False) :
  Size = 0
  for filename in files :
    Size += os.path.getsize(os.path.join(root,filename))
  print root,Size/1024

問題 2 遍歷一個文件夾的子目錄,不遍歷子目錄的字目錄?

os.listdir(path) 函數列出指定目錄下的文件和文件夾

dir = ‘c:/windows‘
if os.path.exists(dir):
  dirs = os.listdir(dir)
  for dirc in dirs:
    print dirc
else :
  print "dir not exists"

python實現文件夾遍歷