美文网首页
python格式化输出文件夹下所有文件

python格式化输出文件夹下所有文件

作者: 土豆肉丝盖浇饭 | 来源:发表于2019-05-21 00:24 被阅读0次

    python2.7

    想格式化列出一个文件夹下面所有的文件夹以及文件,不想用java写(跑java程序挺麻烦),用shell写也挺麻烦,觉得用python做这个事情挺合适的

    ## listfile.python
    import os
    import sys
    
    def list(directory,level):
        paths = os.listdir(directory)
        for path in paths:
            for i in range(1,level):
                sys.stdout.write("--")
            print path
            if os.path.isfile(directory+"/"+path) == False:
                list(directory+"/"+path,level+1)
    
    list(sys.argv[1],2)
    

    使用方式

    python listfile.python `pwd`
    

    效果如下

    --org
    ----springframework
    ------boot
    --------loader
    ----------archive
    ------------ExplodedArchive$1.class
    ------------Archive.class
    ------------ExplodedArchive$FileEntry.class
    ------------Archive$Entry.class
    ------------Archive$EntryFilter.class
    ------------ExplodedArchive$FileEntryIterator.class
    ------------JarFileArchive$JarFileEntry.class
    ------------JarFileArchive.class
    ------------ExplodedArchive.class
    ------------ExplodedArchive$FileEntryIterator$EntryComparator.class
    ------------JarFileArchive$EntryIterator.class
    

    上面一些知识点

    1. 默认print输出会换行并且带空格,这边使用了sys.stdout.write
    2. 递归方法
    3. 使用sys.argv[1]接受传入的参数,sys.argv[1]是当前这个py文件的名字
    4. pwd相当于把执行的pwd shell命令结果作为python脚本参数

    相关文章

      网友评论

          本文标题:python格式化输出文件夹下所有文件

          本文链接:https://www.haomeiwen.com/subject/ujurzqtx.html