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. jdk1.6,jdk1.7共存

    当然可以,安装的时候记得选择不同的安装目录,安装好以后,可以在开发工具(如eclipse)中切换不同的编译环境和运行环境.其实只要安装eclipse就自带了jdk1.3-1.6的编译环境了. Mac下 ...

  2. SQL分类取每一类第一项

    实际应用中经常会碰到这样的需求,在给定的数据集中要求返回每一类型中最大的一条,抑或是最小的一条,抑或是按时间排序最近的一条等等.很多人面对这样的需求显得束手无策,其实这个需求实现有很多种方法,今天给大 ...

  3. Oracle 转换函数

    Oracle 转换函数 -- TO_CHAR(date|number {,fmt} {,nlsparams}) fmt:格式内容,返回的字符串是什么格式的,在此处指定:nlsparams:指定国家语言 ...

  4. T-SQL变量

    T-SQL中变量分为全局变量和局部变量,分别使用@@和@前缀. 全局变量 常用的全局变量有@@VERSION .@@IDENTITY.@@ERROR.@@ROWCOUNT 用法 select @@VE ...

  5. php 实现二进制加法运算

    php实现二进制加法: 思路:没有工作中应用过此场景,但十进制的加法还是经常做的,能不能用十进制加法变相实现呢? 答案是可以的,并且php也提供进制间转换的函数,我的实现使用了 bindec():二进 ...

  6. Php开源项目大全

    WordPress  [PHP开源 博客Blog] WordPress是最热门的开源个人信息发布系统(Blog)之一,基于PHP+MySQL构建.WordPress提供的功能包括: 1.文章发布.分类 ...

  7. Row versus Set Processing, Surprise!(集合处理和单行处理数据的差异性)

    Row versus Set Processing, Surprise! Craig Shallahamer: 1. Set based processing will likely be much ...

  8. light oj 1027 A Dangerous Maze

    一道数学期望题,唉唉,概率论学的不好啊~~ 求走出迷宫的期望时间. 由于有的门会回到起点,所以有可能会走很多遍,设能走出去的门的个数为n1,总的个数为n,那么一次走出去的概率为n1/n,走一次的用的平 ...

  9. 加密传输SSL协议8_Apache服务器的安装

    学习了那么多的理论的知识,下面通过在Apache服务器中安装和使用SSL协议,实现安全传输,但是首先要安装好Apache服务器. Apache服务器的安装 Linux下所有的软件的原码的安装都是三部曲 ...

  10. [置顶] ubuntu12.04下编译opencv程序

    ubuntu12.04下编译opencv程序 1.在ubuntu下安装好 opencv后(建议使用apt-get install 来安装) 2.使用程序FaceExaple.c来进行测试程序 #inc ...