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. Java中,当表单含有文件上传时,提交数据的如何读取

    http://blog.csdn.net/lian_zhihui1984/article/details/6822201

  2. nginx-gridfs 的安装配置和使用

    (一)安装nginx前的准备 安装nginx需要安装openssl和pcre,具体安装步骤请参考nginx安装的相关博文 (二)nginx和nginx-gridfs 联合编译安装 nginx-grid ...

  3. ESMOD北京高级时装艺术学校_百度百科

    ESMOD北京高级时装艺术学校_百度百科 ESMOD北京高级时装艺术学校

  4. 适合入门自学服装裁剪滴书(更新ing)

    [♣]适合入门自学服装裁剪滴书(更新ing) [♣]适合入门自学服装裁剪滴书(更新ing) 适合入门自学服装裁剪滴书(更新ing) 来自: 裁缝阿普(不为良匠,便为良医.) 2014-04-06 23 ...

  5. MD5 32位、16位加密

    /// <summary> /// MD5 16位加密 /// </summary> /// <param name="ConvertString"& ...

  6. #include <sstream>

    1 std::istringstream 2 std::stringstream 1 std::istringstream input 1 在一个字符串string里提取部分数据,这些数据以空格' ' ...

  7. EasyList China国内镜像

    镜像地址: http://www.ikay.me/list/easylistchina.txt 与官方服务器每15分钟同步一次 本文固定链接: http://www.ikay.me/easylistc ...

  8. 2015-01-15百度地图API 新海量点

    整理一下昨天写的百度地图 项目最开始写了一个百度地图,但是速度那慢的简直了 所以昨天将百度地图API的海量点 写了一下 1秒啊 o.o  厉害 OK 记下 此乃需要的js <!--添加百度地图- ...

  9. DevExpress控件之:ChartControl 动态绑定数据

    private void BindData(ViewType vt) { chartControl1.Series.Clear(); //Series series1 = new Series(&qu ...

  10. wcf系列学习5天速成——第五天 服务托管

    今天是系列的终结篇,当然要分享一下wcf的托管方面的知识. wcf中托管服务一般有一下四种: Console寄宿:             利于开发调试,但不是生产环境中的最佳实践. winform寄 ...