遞歸剃袍、深度優(yōu)先错沽、廣度優(yōu)先 實現目錄內文件的遍歷

os.path.join()函數

語法:

os.path.join(path1[,path2[,......]])

返回值:

將多個路徑組合后返回

注:第一個絕對路徑之前的參數將被忽略

import os
def getall(path):
    filelist = os.listdir(path)
    for filename in filelist:
        filepath = os.path.join(path,filename)
        if os.path.isdir(filepath):
            getall(filepath)
            print("目錄:",filepath)
        else:
            print("文件:",filename)
getall(r"/Users/miraco/PycharmProjects")   ##here to type 路徑,以這個路徑為例

輸出:

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/miraco/PycharmProjects/untitled/test333.py
文件: .DS_Store
文件: pimrc2017.txt
文件: pimrc2017.txt
文件: globecom2017.txt
文件: wcnc2017.txt
目錄: /Users/miraco/PycharmProjects/Paper Research/所有文章
文件: 物聯網.txt
目錄: /Users/miraco/PycharmProjects/Paper Research/物聯網
文件: .DS_Store
文件: 眾包.txt
目錄: /Users/miraco/PycharmProjects/Paper Research/眾包
文件: Combining Dynamic Clustering and Scheduling for Coordinated Multi-Point Transmission in LTE.pdf
文件: Capacity of Infrastructure-based Cooperative Vehicular Networks.pdf
文件: Cooperative Transmission in Cognitive and Energy Harvesting-based D2D Networks.pdf
文件: .DS_Store
文件: Cournot-Nash Equilibria for Bandwidth Allocation under Base-Station Cooperation.pdf
文件: A Benchmark for D2D in Cellular Networks- The Importance of Information.pdf
文件: Mobility Aware Caching Incentive Scheme for D2D Cellular Networks.pdf
文件: Hybrid Coordination Function Controlled Channel Access for Latency-Sensitive Tactile Applications .pdf
文件: 協(xié)作通信調研結果:.docx
文件: An Optimal LTE-V2I-Based Cooperative Communication Scheme for Vehicular Networks.pdf
文件: A D2D Mode Selection Scheme with Energy Consumption Minimization Underlaying Two-tier Heterogeneous Cellular Networks.pdf
文件: 08292169.pdf
文件: Power Allocation for Full-Duplex Cooperative Non-Orthogonal Multiple Access Systems.pdf
文件: ON:OFF Reporting Mechanism for Robust Cooperative Sensing in Cognitive IoT Networks.pdf
文件: 協(xié)作通信.txt
文件: User Scheduling for Non-orthogonal Transmission in UAV-Assisted Relay Network.pdf
文件: Computation Collaboration in Ultra Dense Network Integrated with Mobile Edge Computing.pdf
文件: High-Throughput and Fair Scheduling for Access Point Cooperation in Dense Wireless Networks.pdf
目錄: /Users/miraco/PycharmProjects/Paper Research/協(xié)作通信
文件: Delay Efficient Disconnected RSU Placement Algorithm for VANET Safety Applications.pdf
文件: On the Handover Security Key Update and Residence Management in LTE Networks.pdf
文件: Increasing the Security of Wireless Communication Through Relaying and Interference Generation.pdf
文件: A Semi-Outsourcing Secure Data Privacy Scheme for IoT Data Transmission.pdf
文件: Security Enhancement to Successive Interference Cancellation Algorithm for Non-Orthogonal Multiple Access (NOMA).pdf
文件: Lightweight and Privacy-preserving Fog-assisted Information Sharing Scheme for Health Big Data.pdf
文件: A Comparative Study of Possible Solutions for Transmission of Vehicular Safety Messages in LTE-based Networks.pdf
文件: Privacy-Aware Offloading in Mobile-Edge Computing.pdf
文件: 安全隱私.txt
文件: Towards Scalable and Privacy Preserving Commercial Content Dissemination in Social Wireless Networks.pdf
文件: Fairness and Safety Capacity Oriented Resource Allocation Scheme for D2D Communications.pdf
文件: Physical Layer Security in D2D-enabled Cellular Networks- Artificial Noise Assisted.pdf
文件: Privacy-Preserving Data Forwarding in VANETs- A Personal-Social Behavior Based Approach.pdf
文件: Privacy-preserving and Multi-dimensional Range Query in Two-tiered Wireless Sensor Networks.pdf
文件: UAV Assisted Public Safety Communications with LTE-Advanced HetNets and FeICIC.pdf
文件: Dependent Interferer Arrangement for Physical Layer Security- Secrecy Outage Probability in Clustered Wireless Networks.pdf
文件: A Load Balancing Scheme for Supporting Safety Applications in Heterogeneous Software Defined LTE-V Networks.pdf
文件: Promoting Security and Efficiency in D2D Underlay Communication- A Bargaining Game Approach.pdf
文件: Enhancing Physical Layer Security of OFDM Systems Using Channel Shortening.pdf
目錄: /Users/miraco/PycharmProjects/Paper Research/安全隱私
文件: Content-Centric Event-Insensitive Big Data Reduction in Internet of Things .pdf
文件: Twitter as a Source for Spatial Traffic Information in Big Data-Enabled Self-Organizing Networks.pdf
文件: Edge Big Data-Enabled Low-Cost Indoor Localization Based on Bayesian Analysis of RSS.pdf
文件: Reliable Content Dissemination in Internet of Vehicles Using Social Big Data.pdf
文件: Big Data Driven Similarity Based U-Model for Online Social Networks.pdf
文件: Lightweight and Privacy-preserving Fog-assisted Information Sharing Scheme for Health Big Data.pdf
文件: Multi-Keyword Fuzzy and Sortable Ciphertext Retrieval Scheme for big data .pdf
文件: Profit Maximization Auction and Data Management in Big Data Markets.pdf
文件: 大數據.txt
文件: Features Selection Model for Internet of e-Health Things using Big Data.pdf
文件: A Big Data Deep Reinforcement Learning Approach to Next Generation Green Wireless Networks.pdf
文件: Big Data Synchronization among Isolated Data Servers in Disaster.pdf
文件: A Hybrid Location Privacy Protection Scheme in Big Data Environment.pdf
目錄: /Users/miraco/PycharmProjects/Paper Research/大數據
文件: 自組織和傳感器.txt
目錄: /Users/miraco/PycharmProjects/Paper Research/自組織和傳感器
文件: downtitle.cpython-36.pyc
目錄: /Users/miraco/PycharmProjects/Paper Research/__pycache__
文件: researching.py
文件: 干擾協(xié)調管理緩解.txt
目錄: /Users/miraco/PycharmProjects/Paper Research/干擾協(xié)調管理緩解
文件: D2d中繼.txt
目錄: /Users/miraco/PycharmProjects/Paper Research/D2d中繼
文件: 車聯網.txt
目錄: /Users/miraco/PycharmProjects/Paper Research/車聯網
文件: downtitle.py
文件: sortandfilter.py
文件: globecom2017.txt
文件: researching.py
文件: downtitle.py
文件: sortandfilter.py
文件: 運行腳本之前閱讀.rtf
目錄: /Users/miraco/PycharmProjects/Paper Research/代碼
文件: wcnc2017.txt
文件: A Contract-Based Incentive Mechanism for Data Caching in Ultra-Dense Small-Cells Networks .pdf
文件: Mobility Aware Caching Incentive Scheme for D2D Cellular Networks.pdf
文件: Fine-grained Incentive Mechanism for Sensing Augmented Spectrum Database.pdf
文件: Distributed Caching via Rewarding- An Incentive Caching Model for ICN.pdf
文件: QoS-based Incentive Mechanism for Mobile Data Offloading.pdf
文件: Incentive Mechanism for Cached-Enabled Small Cell Sharing- A Stackelberg Game Approach.pdf
文件: 合作激勵.txt
文件: 合作激勵調研.docx
文件: Incentive Based Cooperative Content Caching in Social Wireless Networks.pdf
目錄: /Users/miraco/PycharmProjects/Paper Research/合作激勵
目錄: /Users/miraco/PycharmProjects/Paper Research
文件: .DS_Store
文件: convert.py
文件: test.py
文件: replica.conf.txt
文件: hosts.txt
文件: leetcode.py
文件: hosts2.txt
文件: encodings.xml
文件: hosts.iml
文件: profiles_settings.xml
目錄: /Users/miraco/PycharmProjects/hosts/.idea/inspectionProfiles
文件: workspace.xml
文件: modules.xml
文件: misc.xml
目錄: /Users/miraco/PycharmProjects/hosts/.idea
目錄: /Users/miraco/PycharmProjects/hosts
文件: .DS_Store
文件: 666.py
文件: Wcnc151617Statistics.py
文件: Globecom141516.py
文件: WCNC2015.py
文件: downtitle.cpython-36.pyc
文件: exp3.cpython-36.pyc
文件: exp2.cpython-36.pyc
文件: exp.cpython-36.pyc
目錄: /Users/miraco/PycharmProjects/untitled/__pycache__
文件: test.py
文件: exp2.py
文件: exp3.py
文件: downtitle.py
文件: test333.py
文件: exp.py
文件: encodings.xml
文件: profiles_settings.xml
目錄: /Users/miraco/PycharmProjects/untitled/.idea/inspectionProfiles
文件: workspace.xml
文件: untitled.iml
文件: modules.xml
文件: misc.xml
目錄: /Users/miraco/PycharmProjects/untitled/.idea
目錄: /Users/miraco/PycharmProjects/untitled

當然還可以放在列表里面,一起輸出昂浩狻:

import os
allfilepath = []
allfilename = []
def getall(path):
    filelist = os.listdir(path)
    for filename in filelist:
        filepath = os.path.join(path,filename)
        if os.path.isdir(filepath):
            getall(filepath)
        else:
            allfilename.append(filename)

getall(r"/Users/miraco/PycharmProjects")   ##here to type 路徑
print("文件:", allfilename)
輸出的文件

遍歷的方式有好幾種惹悄,深度遍歷和廣度遍歷

使用深度遍歷進行模擬壓棧

def getall(path):
    realfilelist = []
    mystack = []
    #壓棧
    mystack.append(path)

    while len(mystack)!=0:
        #出棧
        openpath = mystack.pop()
        #找出目錄下的所有文件
        filelist = os.listdir(openpath)
        for filename in filelist:
            abspath = os.path.join(openpath,filename)  #這生成個絕對路徑
            if os.path.isdir(abspath):
            #是目錄春叫,就壓棧
                mystack.append(abspath)
            else:
                #是文件
                realfilelist.append(abspath)
    return realfilelist
arr = getall(r"/Users/miraco/PycharmProjects")
for item in arr:
    print(item)

輸出結果:


image.png

說說collection模塊(資料來自廖雪峰)

collections是Python內建的一個集合模塊,提供了許多有用的集合類泣港。

namedtuple

我們知道tuple可以表示不變集合象缀,例如,一個點的二維坐標就可以表示成:

>>> p = (1, 2)

但是爷速,看到(1, 2)央星,很難看出這個tuple是用來表示一個坐標的。

定義一個class又小題大做了惫东,這時莉给,namedtuple就派上了用場:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(1, 2)
>>> p.x
1
>>> p.y
2

namedtuple是一個函數,它用來創(chuàng)建一個自定義的tuple對象廉沮,并且規(guī)定了tuple元素的個數颓遏,并可以用屬性而不是索引來引用tuple的某個元素。

這樣一來滞时,我們用namedtuple可以很方便地定義一種數據類型叁幢,它具備tuple的不變性,又可以根據屬性來引用坪稽,使用十分方便曼玩。

可以驗證創(chuàng)建的Point對象是tuple的一種子類:

>>> isinstance(p, Point)
True
>>> isinstance(p, tuple)
True

類似地鳞骤,如果要用坐標和半徑表示一個圓,也可以用namedtuple定義:

# namedtuple('名稱', [屬性list]):
Circle = namedtuple('Circle', ['x', 'y', 'r'])

deque

使用list存儲數據時黍判,按索引訪問元素很快豫尽,但是插入和刪除元素就很慢了,因為list是線性存儲顷帖,數據量大的時候美旧,插入和刪除效率很低。

deque是為了高效實現插入和刪除操作的雙向列表贬墩,適合用于隊列和棧:

>>> from collections import deque
>>> q = deque(['a', 'b', 'c'])
>>> q.append('x')
>>> q.appendleft('y')
>>> q
deque(['y', 'a', 'b', 'c', 'x'])

deque除了實現list的append()pop()外榴嗅,還支持appendleft()popleft(),這樣就可以非常高效地往頭部添加或刪除元素陶舞。

defaultdict

使用dict時录肯,如果引用的Key不存在,就會拋出KeyError吊说。如果希望key不存在時论咏,返回一個默認值,就可以用defaultdict

>>> from collections import defaultdict
>>> dd = defaultdict(lambda: 'N/A')
>>> dd['key1'] = 'abc'
>>> dd['key1'] # key1存在
'abc'
>>> dd['key2'] # key2不存在颁井,返回默認值
'N/A'

注意默認值是調用函數返回的厅贪,而函數在創(chuàng)建defaultdict對象時傳入。

除了在Key不存在時返回默認值雅宾,defaultdict的其他行為跟dict是完全一樣的养涮。

OrderedDict

使用dict時,Key是無序的眉抬。在對dict做迭代時贯吓,我們無法確定Key的順序。

如果要保持Key的順序蜀变,可以用OrderedDict

>>> from collections import OrderedDict
>>> d = dict([('a', 1), ('b', 2), ('c', 3)])
>>> d # dict的Key是無序的
{'a': 1, 'c': 3, 'b': 2}
>>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> od # OrderedDict的Key是有序的
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

注意悄谐,OrderedDict的Key會按照插入的順序排列,不是Key本身排序:

>>> od = OrderedDict()
>>> od['z'] = 1
>>> od['y'] = 2
>>> od['x'] = 3
>>> list(od.keys()) # 按照插入的Key的順序返回
['z', 'y', 'x']

OrderedDict可以實現一個FIFO(先進先出)的dict库北,當容量超出限制時爬舰,先刪除最早添加的Key:

from collections import OrderedDict

class LastUpdatedOrderedDict(OrderedDict):

    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self._capacity = capacity

    def __setitem__(self, key, value):
        containsKey = 1 if key in self else 0
        if len(self) - containsKey >= self._capacity:
            last = self.popitem(last=False)
            print('remove:', last)
        if containsKey:
            del self[key]
            print('set:', (key, value))
        else:
            print('add:', (key, value))
        OrderedDict.__setitem__(self, key, value)

Counter

Counter是一個簡單的計數器,例如寒瓦,統(tǒng)計字符出現的個數:

>>> from collections import Counter
>>> c = Counter()
>>> for ch in 'programming':
...     c[ch] = c[ch] + 1
...
>>> c
Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})

Counter實際上也是dict的一個子類情屹,上面的結果可以看出,字符'g'杂腰、'm'垃你、'r'各出現了兩次,其他字符各出現了一次。

廣度優(yōu)先遍歷先進先出

import os
import collections


def getall(path):
    queue = collections.deque([])  #一個隊列
    realfilelist = []  #列表惜颇,用來放文件名
    #進入隊列
    queue.append(path)

    while len(queue) != 0:
        onepath = queue.popleft()  #先進先出的隊列皆刺,最左端取出元素
        filelist  = os.listdir(onepath)    #列出取出元素的目錄的元素
        for filename in filelist:     #檢索每個文件(夾)
            abspath = os.path.join(onepath,filename)     #合成絕對路徑
            if os.path.isdir(abspath):        #如果路徑是是文件夾
                queue.append(abspath)         #進入隊列
            else:
                realfilelist.append(abspath)   #如果是文件就輸出文件名
    return realfilelist

arr = getall(r"/Users/miraco/PycharmProjects")
for item in arr:
    print(item)
···
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市官还,隨后出現的幾起案子芹橡,更是在濱河造成了極大的恐慌毒坛,老刑警劉巖望伦,帶你破解...
    沈念sama閱讀 222,464評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異煎殷,居然都是意外死亡屯伞,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 95,033評論 3 399
  • 文/潘曉璐 我一進店門豪直,熙熙樓的掌柜王于貴愁眉苦臉地迎上來劣摇,“玉大人,你說我怎么就攤上這事弓乙∧┤冢” “怎么了?”我有些...
    開封第一講書人閱讀 169,078評論 0 362
  • 文/不壞的土叔 我叫張陵暇韧,是天一觀的道長勾习。 經常有香客問我,道長懈玻,這世上最難降的妖魔是什么巧婶? 我笑而不...
    開封第一講書人閱讀 59,979評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮涂乌,結果婚禮上艺栈,老公的妹妹穿的比我還像新娘。我一直安慰自己湾盒,他們只是感情好湿右,可當我...
    茶點故事閱讀 69,001評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著罚勾,像睡著了一般诅需。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上荧库,一...
    開封第一講書人閱讀 52,584評論 1 312
  • 那天堰塌,我揣著相機與錄音,去河邊找鬼分衫。 笑死场刑,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播牵现,決...
    沈念sama閱讀 41,085評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼铐懊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了瞎疼?” 一聲冷哼從身側響起科乎,我...
    開封第一講書人閱讀 40,023評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎贼急,沒想到半個月后茅茂,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 46,555評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡太抓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,626評論 3 342
  • 正文 我和宋清朗相戀三年空闲,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片走敌。...
    茶點故事閱讀 40,769評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡碴倾,死狀恐怖,靈堂內的尸體忽然破棺而出掉丽,到底是詐尸還是另有隱情跌榔,我是刑警寧澤,帶...
    沈念sama閱讀 36,439評論 5 351
  • 正文 年R本政府宣布捶障,位于F島的核電站僧须,受9級特大地震影響,放射性物質發(fā)生泄漏残邀。R本人自食惡果不足惜皆辽,卻給世界環(huán)境...
    茶點故事閱讀 42,115評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望芥挣。 院中可真熱鬧驱闷,春花似錦、人聲如沸空免。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,601評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蹋砚。三九已至扼菠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間坝咐,已是汗流浹背循榆。 一陣腳步聲響...
    開封第一講書人閱讀 33,702評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留墨坚,地道東北人秧饮。 一個月前我還...
    沈念sama閱讀 49,191評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親盗尸。 傳聞我的和親對象是個殘疾皇子柑船,可洞房花燭夜當晚...
    茶點故事閱讀 45,781評論 2 361

推薦閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現泼各,斷路器鞍时,智...
    卡卡羅2017閱讀 134,714評論 18 139
  • 〇、前言 本文共108張圖扣蜻,流量黨請慎重逆巍! 歷時1個半月,我把自己學習Python基礎知識的框架詳細梳理了一遍弱贼。 ...
    Raxxie閱讀 18,968評論 17 410
  • 官網 中文版本 好的網站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,407評論 0 5
  • 1.能量負平衡是科學減脂的必要條件之一 健康減肥的關鍵是能量負平衡蒸苇,攝入比消耗少磷蛹。要少吃吮旅、多動、平衡味咳。 2.計算...
    Rainbowchan閱讀 754評論 0 51
  • 小三兒今年十六歲了罕拂,他的父親李三也失蹤了十六年。故事要從十六年前說起全陨,那一年小三兒剛出生爆班,體弱多病,大夫束手無策辱姨,...
    欣蕓閱讀 3,744評論 0 1