python目錄操作之python遍曆檔案夾後將結果儲存為xml_python

來源:互聯網
上載者:User

Linux伺服器有CentOS、Fedora等,都預先安裝了Python,版本從2.4到2.5不等,而Windows類型的伺服器也多數安裝了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:\\apache2\htdocs,然後執行c:\python25\python.exe filesearch.py(這裡假設python的安裝目錄是c:\python25)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.