日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 文件操作 os.walk() 方法

發(fā)布時(shí)間:2025/3/19 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 文件操作 os.walk() 方法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
all = os.walk(source_txt_path)# dirpath:從all中存儲(chǔ)的source_txt_path下文件夾及子文件夾列表中取出每個(gè)文件夾及子文件夾路徑 # dirnames :dirpath下的文件夾列表(不包括子文件夾) # filenames :dirpath下的文件列表 for dirpath, dirnames, filenames in all:

topdown、onerror、followlinks參數(shù)貌似還不怎么用到,暫時(shí)不管。


doc:

def walk(top, topdown=True, onerror=None, followlinks=False):"""Directory tree generator. 目錄樹生成器。For each directory in the directory tree rooted at top(對于以目錄樹為根的目錄中的每個(gè)目錄) (including top itself, but excluding(不包括) '.' and '..'), yields(產(chǎn)生) a 3-tupledirpath, dirnames, filenamesdirpath is a string, the path to the directory. dirnames is a list ofthe names of the subdirectories in dirpath (excluding '.' and '..').dirpath是一個(gè)字符串,是目錄的路徑。 dirnames是dirpath中子目錄名稱的列表filenames is a list of the names of the non-directory files in dirpath.Note that the names in the lists are just names, with no path components.To get a full path (which begins with top) to a file or directory indirpath, do os.path.join(dirpath, name).filenames是dirpath中非目錄文件名稱的列表。 請注意,列表中的名稱只是名稱,沒有路徑成分。 要獲取目錄路徑中文件或目錄的完整路徑(從頂部開始),請執(zhí)行os.path.join(dirpath,name)。If optional arg 'topdown' is true or not specified, the triple for adirectory is generated before the triples for any of its subdirectories(directories are generated top down). If topdown is false, the triplefor a directory is generated after the triples for all of itssubdirectories (directories are generated bottom up).如果可選參數(shù)arg'topdown'為true或未指定,則在其任何子目錄的三元組之前生成目錄的三元組(目錄是自上而下生成的)。 如果topdown為false,則在其所有子目錄的三元組之后生成目錄的三元組(目錄自下而上生成)。When topdown is true, the caller can modify the dirnames list in-place(e.g., via del or slice assignment), and walk will only recurse into thesubdirectories whose names remain in dirnames; this can be used to prune thesearch, or to impose a specific order of visiting. Modifying dirnames whentopdown is false is ineffective, since the directories in dirnames havealready been generated by the time dirnames itself is generated. No matterthe value of topdown, the list of subdirectories is retrieved before thetuples for the directory and its subdirectories are generated.當(dāng)topdown為true時(shí),調(diào)用者可以就地修改目錄名列表(例如,通過del或slice分配),而walk僅會(huì)遞歸到名稱保留在目錄名中的子目錄中; 這可用于修剪搜索或強(qiáng)加特定的訪問順序。 當(dāng)topdown為false時(shí)修改目錄名無效,因?yàn)槟夸浢旧砩蓵r(shí)已經(jīng)生成了目錄名中的目錄。 無論topdown的值如何,都將在生成目錄及其子目錄的元組之前檢索子目錄的列表。By default errors from the os.scandir() call are ignored. Ifoptional arg 'onerror' is specified, it should be a function; itwill be called with one argument, an OSError instance. It canreport the error to continue with the walk, or raise the exceptionto abort the walk. Note that the filename is available as thefilename attribute of the exception object.默認(rèn)情況下,將忽略os.scandir()調(diào)用中的錯(cuò)誤。 如果指定了可選的arg'onerror',它應(yīng)該是一個(gè)函數(shù); 將使用一個(gè)參數(shù)OSError實(shí)例來調(diào)用它。 它可以報(bào)告錯(cuò)誤以繼續(xù)進(jìn)行遍歷,或者引發(fā)異常以中止遍歷。 請注意,文件名可用作異常對象的文件名屬性。By default, os.walk does not follow symbolic links to subdirectories onsystems that support them. In order to get this functionality, set theoptional argument 'followlinks' to true.缺省情況下,os.walk在支持它們的系統(tǒng)上不跟隨符號鏈接到子目錄。 為了獲得此功能,請將可選參數(shù)'followlinks'設(shè)置為true。Caution: if you pass a relative pathname for top, don't change thecurrent working directory between resumptions of walk. walk neverchanges the current directory, and assumes that the client doesn'teither.注意:如果您為top傳遞了相對路徑名,請不要在恢復(fù)行走之間更改當(dāng)前的工作目錄。 walk永遠(yuǎn)不會(huì)更改當(dāng)前目錄,并假定客戶端也不會(huì)更改當(dāng)前目錄。Example:import osfrom os.path import join, getsizefor root, dirs, files in os.walk('python/Lib/email'):print(root, "consumes", end="")print(sum([getsize(join(root, name)) for name in files]), end="")print("bytes in", len(files), "non-directory files")if 'CVS' in dirs:dirs.remove('CVS') # don't visit CVS directories"""top = fspath(top)dirs = []nondirs = []walk_dirs = []# We may not have read permission for top, in which case we can't# get a list of the files the directory contains. os.walk# always suppressed the exception then, rather than blow up for a# minor reason when (say) a thousand readable directories are still# left to visit. That logic is copied here.# 我們可能沒有top的讀取權(quán)限,在這種情況下,我們無法獲取目錄包含的文件的列表。 # 那時(shí)os.walk總是抑制該異常,而不是因?yàn)?#xff08;盡管如此)當(dāng)仍然有千個(gè)可讀目錄需要訪問時(shí)才因次要原因而崩潰。 # 該邏輯復(fù)制到此處。try:# Note that scandir is global in this module due# to earlier import-*.# 注意,由于較早的import-*,scandir在此模塊中是全局的。scandir_it = scandir(top)except OSError as error:if onerror is not None:onerror(error)returnwith scandir_it:while True:try:try:entry = next(scandir_it)except StopIteration:breakexcept OSError as error:if onerror is not None:onerror(error)returntry:is_dir = entry.is_dir()except OSError:# If is_dir() raises an OSError, consider that the entry is not# a directory, same behaviour than os.path.isdir().# 如果is_dir()引發(fā)OSError,請考慮該條目不是目錄,其行為與os.path.isdir()相同。is_dir = Falseif is_dir:dirs.append(entry.name)else:nondirs.append(entry.name)if not topdown and is_dir:# Bottom-up: recurse into sub-directory, but exclude symlinks to# directories if followlinks is False# 自下而上:遞歸到子目錄,但如果followlinks為False,則排除指向目錄的符號鏈接if followlinks:walk_into = Trueelse:try:is_symlink = entry.is_symlink()except OSError:# If is_symlink() raises an OSError, consider that the# entry is not a symbolic link, same behaviour than# os.path.islink().# 如果is_symlink()引發(fā)OSError,請考慮該條目不是符號鏈接,其行為與os.path.islink()相同。is_symlink = Falsewalk_into = not is_symlinkif walk_into:walk_dirs.append(entry.path)# Yield before recursion if going top down# 如果自上而下,則在遞歸前生成if topdown:yield top, dirs, nondirs# Recurse into sub-directories# 遞歸到子目錄islink, join = path.islink, path.joinfor dirname in dirs:new_path = join(top, dirname)# Issue #23605: os.path.islink() is used instead of caching# entry.is_symlink() result during the loop on os.scandir() because# the caller can replace the directory entry during the "yield"# above.# 問題#23605:在os.scandir()上的循環(huán)期間,使用了os.path.islink()而不是緩存entry.is_symlink()結(jié)果,因?yàn)檎{(diào)用者可以在上面的“ yield”期間替換目錄條目。if followlinks or not islink(new_path):yield from walk(new_path, topdown, onerror, followlinks)else:# Recurse into sub-directories# 遞歸到子目錄for new_path in walk_dirs:yield from walk(new_path, topdown, onerror, followlinks)# Yield after recursion if going bottom up# 如果自下而上,則遞歸后生成yield top, dirs, nondirs

參考文章:Python3 os.walk() 方法

總結(jié)

以上是生活随笔為你收集整理的python 文件操作 os.walk() 方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。