Python Beginner Question 6

Copyright Notice: Welcome to reprint, but please indicate the source and author of the article. https://blog.csdn.net/handsomehuo/article/details/90544777

Problem Description: os.path.isdir () and The os.path.isfile () determines an error occurred when the cycle of the second layer.

Code in question:

#编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。
import os
def findfile(name, path):
        for file in os.listdir(path):
            print(file)
            print(os.path.abspath(file))
            if os.path.isdir(file):
                newpath = os.path.abspath(file)
                findfile(name, newpath)
            else:
                if name in file:
                    a = os.path.abspath(file)
                    print(a)
                    print('文件名是%s' % os.path.split(a)[1], '地址是%s' % os.path.split(a)[0])

We have found through debugging, this recursion program itself is not an error, but if you encounter such a scenario: A folder contains B, B includes C, C to function after the implementation level, even if there is file, will be built-in functions os. path.isdir () judgment is false, very strange.

Fortunately, we did two print output path can be observed by running we found wrong path!

For example, if the file is in /A/B/C/1234.txt, when the file is 1234.txt, os.path.abspath (file) output is actually /A/1234.txt, leading to os.path.isdir ( ) could not find the file, returning a OSError.

So the problem is in os.path.abspath (), which has returned the file name is to perform address + function on this function, very perfunctory! So ostensibly os.path.isdir () problem, but in fact it is wrong about him.

Abspath look at the code at a glance.

def abspath(path):
    """Return an absolute path."""
    path = os.fspath(path)
    if not isabs(path): #判断是否是绝对路径,经判断不是绝对路径
        if isinstance(path, bytes): 
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()#返回函数当前执行路径
        path = join(cwd, path)
    return normpath(path)

The next question then is extended why isabs (path) it would be false, reason out on another function: os.listdir (path).

Look at the official explanation of os.listdir (path) of

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.

At the return '' and the given path alphabetically sorted list '..' outside of all file and directory names.

...

The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.

the scandir () function returns the directory path and file with attributes, better results used in many scenes.

Understand, os.listdir (path) returns only the list with strings, without attributes, regardless of authenticity, the official recommended route we use scandir ().

Therefore, this code should be how to modify it?

There are three ways:

1, os.walk, not self-made wheels.

2, using os.scandir () Replace os.listdir ().

3, with the chdir () Replace directory execution path.

...
os.chdir(file)
newpath = os.path.abspath('.')
print(newpath)
...
os.chdir(os.path.abspath('..'))

 

Guess you like

Origin blog.csdn.net/handsomehuo/article/details/90544777