gpt4 book ai didi

python - 如果路径是文件或目录 (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 18:46:46 25 4
gpt4 key购买 nike

我试图列出当前文件夹中的所有文件以及当前文件夹的文件夹中的文件。这就是我一直在做的事情:

import os


def sendFnF(dirList):
for file in dirList:

if os.path.isdir(file):
print 'Going in dir:',file
dirList1= os.listdir('./'+file)
# print 'files in list', dirList1
sendFnF(dirList1)
print 'backToPrevDirectory:'

else:
print 'file name is',file




filename= raw_input()
dirList= os.listdir('./'+filename)
sendFnF(dirList)

这段代码确实让我进入了当前目录的文件夹。但是当涉及到子文件夹时;它将它们视为文件。知道我做错了什么吗?提前致谢,中士。

最佳答案

在路径前面添加 ./ 基本上没有任何作用。另外,仅仅因为您使用目录路径递归调用函数并不会更改当前目录,因此文件路径中 . 的含义也不会更改。

您的基本方法是正确的,使用 os.path.join() 进入目录。最好重构您的代码,以便在 sendFnF() 开头使用 listdir():

def sendFnF(directory):
for fname in os.listdir(directory):
# Add the current directory to the filename
fpath = os.path.join(directory, fname)

# You need to check the full path, not just the filename
if os.path.isdir(fpath):
sendFnF(fpath)
else:
# ...

# ...
sendFnf(filename)

也就是说,除非这是练习,否则您可以使用 os.walk()

关于python - 如果路径是文件或目录 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19349037/

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