python目錄操作之python遍歷文件夾后將結(jié)果存儲為xml
Linux服務(wù)器有CentOS、Fedora等,都預(yù)先安裝了Python,版本從2.4到2.5不等,而Windows類型的服務(wù)器也多數(shù)安裝了Python,因此只要在本機寫好一個腳本,上傳到對應(yīng)機器,在運行時修改參數(shù)即可。
Python操作文件和文件夾使用的是os庫,下面的代碼中主要用到了幾個函數(shù):
os.listdir:列出目錄下的文件和文件夾
os.path.join:拼接得到一個文件/文件夾的全路徑
os.path.isfile:判斷是否是文件
os.path.splitext:從名稱中取出一個子部分
下面是目錄操作的代碼
def search(folder, filter, allfile):
folders = os.listdir(folder)
for name in folders:
curname = os.path.join(folder, name)
isfile = os.path.isfile(curname)
if isfile:
ext = os.path.splitext(curname)[1]
count = filter.count(ext)
if count>0:
cur = myfile()
cur.name = curname
allfile.append(cur)
else:
search(curname, filter, allfile)
return allfile
在返回文件的各種信息時,使用自定義類allfile來保存文件的信息,在程序中只用到了文件的全路徑,如果需要同時記錄文件的大小、時間、類型等信息,可以仿照代碼進行擴充。
class myfile:
def __init__(self):
self.name = ""
得到存儲文件信息的數(shù)組后,還可以將其另存成xml格式,下面是代碼,在使用時,需要從Document中導(dǎo)入xml.dom.minidom
下面是保存為xml的代碼
def generate(allfile, xml):
doc = Document()
root = doc.createElement("root")
doc.appendChild(root)
for myfile in allfile:
file = doc.createElement("file")
root.appendChild(file)
name = doc.createElement("name")
file.appendChild(name)
namevalue = doc.createTextNode(myfile.name)
name.appendChild(namevalue)
print doc.toprettyxml(indent="")
f = open(xml, 'a+')
f.write(doc.toprettyxml(indent=""))
f.close()
執(zhí)行的代碼如下
if __name__ == '__main__':
folder = "/usr/local/apache/htdocs"
filter = [".html",".htm",".php"]
allfile = []
allfile = search(folder, filter, allfile)
len = len(allfile)
print "found: " + str(len) + " files"
xml = "folder.xml"
generate(allfile, xml)
在Linux命令行狀態(tài)下,執(zhí)行Python filesearch.py,便可以生成名為folder.xml的文件。
如果要在Windows中運行該程序,需要把folder變量改成Windows下的格式,例如c:\\apache2\htdocs,然后執(zhí)行c:\python25\python.exe filesearch.py(這里假設(shè)python的安裝目錄是c:\python25)
相關(guān)文章
講清楚fit_transform()和transform()的區(qū)別及說明
這篇文章主要介紹了講清楚fit_transform()和transform()的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU
這篇文章主要介紹了tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this T的相關(guān)知識,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06PyTorch如何創(chuàng)建自己的數(shù)據(jù)集
這篇文章主要介紹了PyTorch如何創(chuàng)建自己的數(shù)據(jù)集,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11python設(shè)置Pyplot的動態(tài)rc參數(shù)、繪圖的填充
本文主要介紹了python設(shè)置Pyplot的動態(tài)rc參數(shù)、繪圖的填充,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)實現(xiàn)影評情感分類
這篇文章主要為大家詳細介紹了基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)實現(xiàn)影評情感分類,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03