[英]If a path is file or directory (Python)
我正在尝试列出当前文件夹中的所有文件以及当前文件夹中的文件。 这就是我一直在做的:
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)
这段代码确实使我进入了当前目录的文件夹。 但是当涉及到子文件夹时; 它将它们视为文件。 知道我在做什么错吗? 在此先感谢,Sarge。
在路径前加./
基本上没有任何作用。 另外,仅因为您使用目录路径递归调用函数并不会更改当前目录,因此的含义.
在文件路径中。
您的基本方法是正确的,使用os.path.join()
进入目录。 最好重组代码,以便在listdir()
开始时sendFnF()
:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.