推荐学习书目
› 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 · May 11, 2017 · 4165 views
    This topic created in 3423 days ago, the information mentioned may be changed or developed.

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

    #!/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 replies  •  2017-05-12 07:52:56 +08:00
    mdzz
        1
    mdzz  
       May 11, 2017
    踩过这个坑,os.listdir(path) 的结果需要处理一下才是完整路径
    full_path = os.path.join(path, x)
    264768502
        2
    264768502  
       May 12, 2017 via Android   ❤️ 1
    遍历目录可以用 os.walk,这样就不用递归了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2701 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 03:25 · PVG 11:25 · LAX 20:25 · JFK 23:25
    ♥ Do have faith in what you're doing.