Python檔案遍歷

2021-10-10 10:10:04 字數 1237 閱讀 4423

python檔案遍歷

重點: 以下兩個方法裡面的path都是絕對路徑。

os.path.isdir(path)

os.path.isfile(path)

深度遍歷檔案**如下(借用棧的後進先出的思想實現給定path下檔案的遍歷):

import os

#新建乙個列表

stack =

def getalldirdep(path):

print('**stack element:',stack)

while len(stack) != 0:

dirpath = stack.pop()

print('dirpath:',dirpath)

filelist = os.listdir(dirpath)

print('filelist:',filelist)

for filename in filelist:

fileabspath = os.path.join(dirpath,filename)

if os.path.isdir(fileabspath):

print('%%%%this is a folder:',filename)

#getalldirdep(filename) #wrong code, this is not an abs pathgetalldirdep(fileabspath)else:

print('-----------this is a file',fileabspath)

#呼叫方法

getalldirdep(r"c:\users\***\pycharmprojects\pythonproject")

test abs path

print(os.path.isdir("c:\users\***\pycharmprojects\pythonproject\venv\include")) -- 輸出true

print(os.path.isdir("include")) -- 輸出false

print(os.path.isfile("c:\users\***\pycharmprojects\pythonproject\.idea\misc.xml")) -- 輸出true

print(os.path.isfile("misc.xml")) -- 輸出false

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迴圈遍歷檔案

for遍歷檔案 open aaa.py r readline 遍歷aaa.py的第一行,每個字元作為一行 open aaa.py r readlines 遍歷整個aaa.py文件,源文件一行作為遍歷的一行 open aaa.py r read 遍歷整個aaa.py文件,每個字元作為一行 r 表示已唯...

python遍歷目錄檔案

直接上 os.walk import os from os.path import join,getsize for root,dirs,files in os.walk python lib email print root,consumes print sum getsize join root...