gpt4 book ai didi

python - 使用 os.walk() 生成包含中间目录的文件名

转载 作者:行者123 更新时间:2023-12-01 09:28:35 24 4
gpt4 key购买 nike

这是我第一次使用 Python 工作,在以下代码段中查找中间目录路径时遇到了一些麻烦:

目前,当将目录参数传递给“stroll”时,该函数似乎进入 thePath,观察每个子目录类型,并按目录类型降序排列。该代码不是我的,而且嵌套的 for 循环似乎正在迭代常规文件列表,因此循环不知道有关每个元素所属目录的任何信息。

当前输出为

../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1
../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1
../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1
../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1

期望的输出是

../Sample_Cases_Asg2/sample1/output.txt
../Sample_Cases_Asg2/sample1/file2
../Sample_Cases_Asg2/sample1/file1
../Sample_Cases_Asg2/sample2/output.txt
../Sample_Cases_Asg2/sample2/file2
../Sample_Cases_Asg2/sample2/file1
../Sample_Cases_Asg2/sample3output.txt
../Sample_Cases_Asg2/sample3/file2
../Sample_Cases_Asg2/sample3/file1
../Sample_Cases_Asg2/sample3/output.txt
../Sample_Cases_Asg2/sample3/file2
../Sample_Cases_Asg2/sample3/file1

实现是

   def stroll(thePath):
deeper = []
for root, dirs, files in os.walk(thePath):
for file in files:
print (os.path.join(thePath, file))

此外,我是社区的新手,因此任何关于如何改进我的提问的简洁意见将不胜感激。

最佳答案

如果将 help(os.walk) 放入 shell 中,您将看到:

For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple

dirpath, dirnames, filenames

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components.

所以你需要:

os.path.join(root, file)

这很烦人。

关于python - 使用 os.walk() 生成包含中间目录的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50143431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com