zoukankan      html  css  js  c++  java
  • python 文件搜索

    练习:编写一个search(s)的函数,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出完整路径:

    $ python search.py test
    unit_test.log
    py/test.py
    py/test_os.py
    my/logs/unit-test-result.txt

    code:

    # -*- coding: utf-8 -*-
    
    'Search a file with its filename'
    __author__='spook' import os num = 0 def search(dirPath,fileName): global num for y in os.listdir(dirPath): absPath = os.path.join(dirPath,y).decode('gbk').encode('utf-8') if os.path.isdir(absPath): try: search(absPath,fileName) except BaseException, e: continue elif (os.path.isfile(absPath) and os.path.split(absPath)[1]==fileName): num +=1 print('found %s '%absPath.decode('gbk').encode('utf-8'))

    #search('D:\CreateFromPDM','README.txt') search('D:\','README.txt') print("%d founded"%num)

    附:split与join

    os.path.split()   按照路径将文件名和路径分割开,比如d:\python\python.ext,可分割为['d:\python', 'python.exe']

    import os
    print os.path.split('c:\Program File\123.doc')
    print os.path.split('c:\Program File\')
    -----------------output---------------------
    ('c:\Program File', '123.doc')
    ('c:\Program File', '')

    os.path.join(path1[,path2[,......]])  split的逆过程

    os.path.join(path1[, path2[, ...]])
    
    将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。
    
    >>> os.path.join('c:\', 'csv', 'test.csv')
    
    'c:\csv\test.csv'
    
    >>> os.path.join('windows	emp', 'c:\', 'csv', 'test.csv')
    
    'c:\csv\test.csv'
    
    >>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')
    
    '/home/aa/bb/c'
  • 相关阅读:
    面试题
    linux I/O复用
    grep
    转载 hadoop 伪分布安装
    hadoop配置文件: hdfs-site.xml, mapred-site.xml
    Format aborted in 格式化namenode 失败的原因
    ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: Incompatible namespaceIDs
    /etc/rc.d/init.d/iptables: No such file or directory 错误原因
    linux配置Hadoop伪分布安装模式
    初学Linux 命令
  • 原文地址:https://www.cnblogs.com/maple42/p/4139751.html
Copyright © 2011-2022 走看看