设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: crossin先生
打印 上一主题 下一主题

【每日一坑 6】 查找文件内容

[复制链接]

1

主题

0

好友

39

积分

新手上路

Rank: 1

楼主
发表于 2017-8-31 11:57:51 |显示全部楼层

import fnmatch
import os


def filterFile(filePath, contain):
    for grandFather, father, sons in os.walk(filePath):
        sonList = []
        for son in sons:
            sonList.append(son)
        fnmatchs = fnmatch.filter(sonList, "*.txt")
        if len(fnmatchs) != 0:
            for fnmatchFile in fnmatchs:
                absultePath = grandFather + "/" + fnmatchFile
                absultePath = absultePath.replace("\\", "/")
                f = file(absultePath)
                str = f.read()
                f.close()
                if str.__contains__(contain):
                    print absultePath


path = raw_input("请输入遍历的绝对路径:")
filterFile(path, "aaa")

做的过程中存在两个问题困扰了我:
1、sonList刚开始在方法外放着,导致生命周期太长,所以导致了我的拼接出来的路径下不存在某个文件
2、拼接出来的路径是双引号的,用来打开文件会出错。但是我敲的demo在pycharm中打印出来却是单斜杠的。一直不知道是哪里出问题了。最后发现是pycharm自动将其转化为合格的路劲。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-3 13:50 , Processed in 0.025205 second(s), 24 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部