Posted on 2012-07-12 13:30
RTY 閱讀(513)
評論(0) 編輯 收藏 引用 所屬分類:
Python 、
轉載隨筆
Python操作文件和文件夾使用的是os庫,下面的代碼中主要用到了幾個函數:
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 = "" |
得到存儲文件信息的數組后,還可以將其另存成xml格式,下面是代碼,在使用時,需要從Document中導入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() |
執行的代碼如下
代碼如下 | 復制代碼 |
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命令行狀態下,執行Python filesearch.py,便可以生成名為folder.xml的文件。
如果要在Windows中運行該程序,需要把folder變量改成Windows下的格式,例如c:\apache2htdocs,然后執行c:python25python.exe filesearch.py(這里假設python的安裝目錄是c:python25)