Quantcast
Channel: panjj 最新博客
Viewing all articles
Browse latest Browse all 59

Python点滴拾遗 文件 目录 file xml dir

$
0
0
最近需要一些Python的东西,搜索了一下,发现了Andy阳光生活 的一篇文章正用上,所以转载了,算是Remark有用的东西。如果对你有用,请连接到原文。以下是他写的内容:
获取文件后缀名 (2009-7-26)
    f = 'test.py';
    ext = f[f.rindex('.'):]
    print ext
统计文件行数 (2009-7-26)
    thefilepath = 'D:\\www\\test\\test.html'
    countLine = 0
    for fileLine in open(thefilepath).xreadlines( ):
        countLine += 1
    print countLine
获取目录大小 (2009-7-26)
    import os
    from os.path import join, getsize
    def getdirsize(dir):   
        size = 0L
        for root, dirs, files in os.walk(dir):
            size += sum([getsize(join(root, name)) for name in files])
        return size
    if __name__ == '__main__':
        print 'Waiting...'
        filesize = getdirsize(r'D:\www\test\python')
        print 'There are %.3f' % (filesize/1024/1024), 'Mbytes in D:\\www\\test\\python'
os.path常见属性
    os.path.sep :路径分隔符 。以前老爱用'\\',后来用'/'。
    os.path.altsep:(根目录)
    os.path.curdir: 当前目录
    os.path.pardir: 父目录
判断是否是指定文件类型
    File.rsplit('.',1)[-1] == type
    当然也可以写成File.split('.')[-1:][0] == type
获取当前路径
    os.getcwd()
改变当前路径
    os.chdir(r"c:/")
修改文件名称
    os.rename("bbb.txt","ccc.txt")
    如果ccc.txt已经存在,则有异常抛出 
文件夹改名
    os.rename("aaa","ccc")
    如果ccc已经存在,则有异常抛出
正则表达式获取文件列表
    import glob
    # 生成当前路径下所有文件的列表
    a = glob.glob('*')
    print a
    # 生成当前路径下所有扩展名为gif的文件列表。
    a = glob.glob('*.gif') 
打印出xml文件的内容
    from xml.dom import minidom
    xmldoc = minidom.parse('binary.xml')
    print xmldoc
    print xmldoc.toxml() 
从url解析xml
    import urllib
    usock = urllib.urlopen('http://www.blogjava.net/JAVA-HE/category/19871.html/rss')
    xmldoc = minidom.parse(usock)
    usock.close()
    print xmldoc.toxml() 
把string解析为xml
    from xml.dom import minidom
    contents = "<grammar><ref id='bit'><p>0</p><p>1</p></ref></grammar>"
    xmldoc = minidom.parseString(contents)
    print xmldoc.toxml()
    <?xml version="1.0" ?><grammar><ref id="bit"><p>0</p><p>1</p></ref></grammar> 
两种遍历目录对比
    >>> files = os.listdir(".")
    >>> for f in files:
    print "." + os.sep + f
    上面这种已经用过了。下面是一种递归遍历的:
    for root, dirs, files in os.walk("."):
    for name in files:
    print os.path.join(root,name) 
    f=open('/tmp/workfile', 'w')
    f.read()
    f.readline()
    f.write('This is a test\n')
    f.seek(5) # 从文件头前进5 个字节,到达第6 个字符
    f.close()
pickle 模块
可以把几乎任何Python对象转换为字符串表示,这个过程叫做腌制,从对象的字符串表示恢复对象叫做恢复。在腌制和反腌制之间,对象的字符串表示可以保存在文件或数据中,甚至于通过网络连接传送到远程计算机上
    pickle.dump(x, f)
    x = pickle.load(f)

Viewing all articles
Browse latest Browse all 59

Trending Articles