我正在尝试计算目录和子目录中的文件数量,它将用于许多我事先不知道的用户,所以我想在路径中使用“~”波浪号。但是当我执行以下操作时,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}")
最佳答案
使用上面的回复,代码现在的工作方式如下:
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}")
关于Python os.walk() 不适用于路径中的波浪号 ~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68754431/