路径突然反斜杠

2024-06-02 06:00:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取获取目录大小的函数。你知道吗

def fsize(path, returntype='b'):
    size = 0
    if isdir(path):
        for root, dirs, files in walk(path):
            for file in files:
                size += getsize(join(path,file))

    else:
        print abspath(path)
        size = getsize(abspath(path))

    if returntype != 'b':
        return convert_size(size, returntype)
    return size

path = r"D:\Library\Daniel's_Books"

print fsize(path, 'm')

我得到一个有趣的错误:

size = getsize(abspath(path))
File "C:\Python27\lib\genericpath.py", line 49, in getsize
return os.stat(filename).st_size
WindowsError: [Error 2] The system cannot find the file specified: "D:\\Library\\Daniel's_Books\\cover.jpg"
D:\Library\Daniel's_Books\cover.jpg

为什么反斜杠反斜杠? 我怎样才能纠正这个错误呢?你知道吗


Tags: pathinforsizereturniflibraryfiles
1条回答
网友
1楼 · 发布于 2024-06-02 06:00:14

关于你的第一个问题

why does it backslash the backslashes?

这只是一个展示的问题。由于\是转义字符,因此可以将\内的字符串指定为r'\''\\'。也就是说,它的显示方式与the ^{} function返回的完全相同。你知道吗

顺便说一句:你的

path = "D:\Library\Daniel's_Books"

问题的原因是一样的:它只起作用,因为\D\L不是有效的转义。你最好把它写成

path = r"D:\Library\Daniel's_Books"

作为原始字符串或

path = "D:\\Library\\Daniel's_Books"

作为带有正确转义的\s的字符串


你的第二个问题

and how can I fix the error?

有点棘手。你知道吗

我认为多重递归有一个问题:一方面,walk()完全遍历树。所以从第二级开始,join(path,file)是错误的,你应该用root替换path。另一方面,递归调用fsize(),这可能会导致文件重复。你知道吗

假设您有以下树:

.
+- A
|  +- a
|  +- b
+- B
|  +- a
|  +- b
+- a
+- b

os.walk()通过为每个目录级别生成root, dirs, files来遍历给定的树。你知道吗

在这个例子中,它将产生

'.', ['A', 'B'], ['a', 'b']
'.\\A', [], ['a', 'b']
'.\\B', [], ['a', 'b']

因此root包含files所在的当前处理目录。你知道吗

我假设您的cover.jpg驻留在Daniel's_Books的子目录中,而不是这个目录本身。将它与正确的目录组合将使它被找到。你知道吗

相关问题 更多 >