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:\apache2htdocs,然后执行c:python25python.exe filesearch.py(这里假设python的安装目录是c:python25)

源码整理:

import os
import sys
from xml.dom.minidom import Document
class myfile:
    def __init__(self):
        self.name = ""

def search(folder, filter, allfile):

print ("in search.....")

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

def generate(allfile, xml):

doc = Document()

print ("in generate.........")

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 = "D:\\mine\\bootstrap-3.3.2\\docs"

filter = [".html",".htm",".php"]

allfile = []

allfile = search(folder, filter, allfile)

len = len(allfile)

print "found: " + str(len) + " files"

xml = "folder.xml"

generate(allfile, xml)

python文件目录遍历保存成xml文件代码的更多相关文章

  1. Android吧数据保存成xml文件

    public class MainActivity extends Activity { private List<Person> persons; @Override protected ...

  2. 微软BI 之SSIS 系列 - 两种将 SQL Server 数据库数据输出成 XML 文件的方法

    开篇介绍 在 SSIS 中并没有直接提供从数据源到 XML 的转换输出,Destination 的输出对象有 Excel File, Flat File, Database 等,但是并没有直接提供 X ...

  3. 提取数据表保存为XML文件

    //连接数据库 SqlConnection con = new SqlConnection("server=****;database=****;uid=sa;pwd=********&qu ...

  4. tcpdump抓包并保存成cap文件

    首选介绍一下tcpdump的常用参数 tcpdump采用命令行方式,它的命令格式为: tcpdump [ -adeflnNOpqStvx ] [ -c 数量 ] [ -F 文件名 ] [ -i 网络接 ...

  5. python中用ElementTree.iterparse()读取xml文件中的多层节点

    我在使用Python解析比较大型的xml文件时,为了提高效率,决定使用iterparse()方法,但是发现根据网上的例子:每次if event == 'end':之后elem.clear()或者是每次 ...

  6. Python Windows下打包成exe文件

    Python Windows 下打包成exe文件,使用PyInstaller 软件环境: 1.OS:Win10 64 位 2.Python 3.7 3.安装PyInstaller 先检查是否已安装Py ...

  7. [python小记]使用lxml修改xml文件,并遍历目录

    这次的目的是遍历目录,把目标文件及相应的目录信息更新到xml文件中.在经过痛苦的摸索之后,从python自带的ElementTree投奔向了lxml.而弃用自带的ElementTree的原因就是,na ...

  8. List<T>保存为XML文件

    今天我们学习怎样把List<T>写成一个XML文件保存起来.因为我们在做动态网站开发时,需要对一些不太常变化的数据产生为XML文件,让程序直接去读取,而不是每次是SQL数据库取. 为了解决 ...

  9. 设置Eclipse的类文件和xml文件代码自动补全

    原文:https://blog.csdn.net/erlian1992/article/details/53706736 我们在平常编写代码的时候,不会记住大多数的类和文件的属性,方法等等,这就需要我 ...

随机推荐

  1. RHEL Channel Bonding

    1. 添加 kernel 模块 RHEL5上编辑 /etc/modprobe.conf 加入 alias bond0 bonding options bond0 miimon=100 mode=1   ...

  2. 打开网页自动弹出QQ临时会话 (打开网站弹出QQ聊天) qq.js文件代

    eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35 ...

  3. java常量池理解

    String类两种不同的创建方式 String s1 = "zheng"; //第一种创建方式 String s2 = new String("junxiang" ...

  4. ubuntu 设置网卡为混杂模式 以及网络配置命令

    1. ifconfig eth0 promisc 设置eth0为混杂模式. ifconfig eth0 -promisc 取消它的混杂模式 botnet@botnet-virtual-machine: ...

  5. JQuery(上)

    1.流行的JavaScript类库   --  框架.插件 )为了简化 JavaScript 的开发, 一些 JavsScript 库诞生了. JavaScript 库封装了很多预定义的对象和实用函数 ...

  6. URAL 1796. Amusement Park (math)

    1796. Amusement Park Time limit: 1.0 second Memory limit: 64 MB On a sunny Sunday, a group of childr ...

  7. HNU 12850 Garage

    长为H的格子里面放n个长为h的格子 最多会有n+1个空隙 要使每一个空隙长度都小于h (H-h*n)/(n+1)<h n>(H/h-1)/2 #include<bits/stdc++ ...

  8. css3前端工具

    随着CSS3的出现,CSS3讨论的话题越来越多了,现在各种教程也是多如牛毛,不比一年前的时候,找个资料要捞遍整个互联网,而且还很难找到自己需要的参考资料.从侧面也说明,CSS3对于前端工程师来说,越来 ...

  9. MyEclipse中SVN的使用方法

    来至转载  -----新浪博客 MyEclipse中的SVN操作手册 1.导入项目 点击工具栏上的[File-Import],进入下图

  10. C#获得命令提示符输出

    原文:http://blog.csdn.net/abrahu/article/details/6611504 C#获得命令提示符输出 分类: c#应用程序2011-07-16 23:34 600人阅读 ...