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)
輸出結果:
說說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)
···