【问题标题】:Python os.walk() does not work with tilde ~ in pathPython os.walk() 不适用于路径中的波浪号 ~
【发布时间】:2021-10-15 15:33:26
【问题描述】:

我正在尝试计算目录和子目录中的文件,它将用于许多我事先不知道的用户,所以我想在路径中使用“~”波浪号。但是当我执行以下操作时,python 什么也不返回:

import os 

for root, dirs, files in os.walk("~/direcotry/sub_directory", topdown=True):
    for name in dirs:
        print(os.path.join(root, name))

    total += len(files)

print(f"Total number of files in directory is:{total}")

【问题讨论】:

  • 试试os.path.expanduser("~")

标签: python linux operating-system os.walk tilde


【解决方案1】:

使用上面的回复代码现在是这样工作的:

import os 

exapnded_dir = os.path.expanduser('~/direcotry/sub_directory')
for root, dirs, files in os.walk(exapnded_dir, topdown=True):
    for name in dirs:
        print(os.path.join(root, name))

    total += len(files)

print(f"Total number of files in directory is:{total}")

【讨论】:

    最近更新 更多