我正在尝试编写一个脚本来列出给定目录中的所有目录、子目录和文件。
我尝试了这个:
import sys, os
root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")
for r, d, f in os.walk(path):
for file in f:
print(os.path.join(root, file))
很遗憾,它不能正常工作。我可以获取所有文件,但无法获取它们的完整路径。
例如,如果目录结构如下:
/home/patate/directory/targetdirectory/123/456/789/file.txt
它会打印:
/home/patate/directory/targetdirectory/file.txt
我需要第一个结果。
print(os.path.join(path, name))
。 - Ehsanos.walk(root)
would inspect all contents ofroot
. if you want to look within the provided directory as said in the original question you should useos.walk(path)
- Gianclgar