V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
LemonFirst
V2EX  ›  Python

[求教]os.path.abspath()输出一直不正确.

  •  
  •   LemonFirst · 2017-05-11 21:03:01 +08:00 · 3428 次点击
    这是一个创建于 2557 天前的主题,其中的信息可能已经有所发展或是发生改变。

    练习想做一个找当前目录以及子目录中匹配指定字符串的小程序.代码如下:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    #author: Lemon
    
    import os
    dirlist = []
    def search(filename,path):
        for x in os.listdir(path):
            if os.path.isdir(x):
                dirlist.append( os.path.abspath(x) )
            elif filename in x:
                print(os.path.abspath(x))
        while len(dirlist)>0 :
            search(filename,dirlist.pop())
    
    if __name__ == '__main__':
       search('qqww','.')
    
    

    然后在 /home/lemon/learnPython 目录下有一个 qqwwqq 的测试文件. 可是执行后输出一直是 /home/lemon/qqwwqq 可以保证 /home/lemon 目录下绝对没有 qqwwqq 这个文件.

    2 条回复    2017-05-12 07:52:56 +08:00
    mdzz
        1
    mdzz  
       2017-05-11 21:21:44 +08:00
    踩过这个坑,os.listdir(path) 的结果需要处理一下才是完整路径
    full_path = os.path.join(path, x)
    264768502
        2
    264768502  
       2017-05-12 07:52:56 +08:00 via Android   ❤️ 1
    遍历目录可以用 os.walk,这样就不用递归了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1217 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:24 · PVG 02:24 · LAX 11:24 · JFK 14:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.