檔案操作之遍歷目錄

2021-06-18 11:52:26 字數 2644 閱讀 8545

原文:

python天天進步--檔案操作之遍歷目錄

python的os模組,包含了普遍的作業系統功能,這裡主要學習與路徑相關的函式:

os.listdir(dirname):列出dirname下的目錄和檔案

os.getcwd():獲得當前工作目錄

os.curdir:返回當前目錄('.')

os.chdir(dirname):改變工作目錄到dirname

os.path.isdir(name):判斷name是不是乙個目錄,name不是目錄就返回false

os.path.isfile(name):判斷name是不是乙個檔案,不存在name也返回false

os.path.exists(name):判斷是否存在檔案或目錄name

os.path.getsize(name):獲得檔案大小,如果name是目錄返回0

os.path.abspath(name):獲得絕對路徑

os.path.normpath(path):規範path字串形式

os.path.split(name):分割檔名與目錄(事實上,如果你完全使用目錄,它也會將最後乙個目錄作為檔名而分離,同時它不會判斷檔案或目錄是否存在)

os.path.splitext():分離檔名與副檔名

os.path.join(path,name):連線目錄與檔名或目錄

os.path.basename(path):返回檔名

os.path.dirname(path):返回檔案路徑  1、

os.path方法

通過傳入需要遍歷的目錄,列出目錄下的所有檔案並統計檔案數,os提供的path模組能對目錄非常靈活的操作。

import os,sys

deflistdir(dir,file):

file.write(dir + '

/n')

fielnum = 0

list = os.listdir(dir)  #列出目錄下的所有檔案和目錄

forline in list:

filepath = os.path.join(dir,line)

ifos.path.isdir(filepath):  #如果filepath是目錄,則再列出該目錄下的所有檔案

myfile.write('   ' + line + '

//'+'

/n')

forli in os.listdir(filepath):

myfile.write('     '+li + '

/n')

fielnum = fielnum + 1

elifos.path:   #如果filepath是檔案,直接列出檔名

myfile.write('   '+line + '

/n') 

fielnum = fielnum + 1

myfile.write('all the file num is '+ str(fielnum))

dir = raw_input('please input the path:')

myfile = open('list.txt','w')

2、os.walk方法

os模組提供的walk方法很強大,能夠把給定的目錄下的所有目錄和檔案遍歷出來。

方法:os.walk(path),遍歷path,返回乙個物件,他的每個部分都是乙個三元組,('目錄x',[目錄x下的目錄list],目錄x下面的檔案)

import os

defwalk_dir(dir,fileinfo,topdown=true):

forroot, dirs, files 

in os.walk(dir, topdown):

forname 

in files:

print(os.path.join(name))

fileinfo.write(os.path.join(root,name) + 

'/n')

forname 

in dirs:

print(os.path.join(name))

fileinfo.write(

'  ' + os.path.join(root,name) + 

'/n')

dir = raw_input(

'please input the path:')

fileinfo = open(

'list.txt',

'w')

walk_dir(dir,fileinfo)

topdown決定遍歷的順序,如果topdown為true,則先列舉top下的目錄,然後是目錄的目錄,依次類推,反之,則先遞迴列舉出最深層的子目錄,然後是其兄弟目錄,然後子目錄。

~~~~~~~~~belive yourself ,nothing is impossible, write in 02.

13.2009 by vivilorne~~~~~~~

檔案操作之遍歷目錄

os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.path.isdir name 判斷name是不是乙個目錄,name不是目錄就返回fa...

Python 檔案操作之遍歷目錄

python的os模組,包含了普遍的作業系統功能,這裡主要學習與路徑相關的函式 os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.pat...

python天天進步 檔案操作之遍歷目錄

python天天進步 檔案操作之遍歷目錄 os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.path.isdir name 判斷name...