Ответ 1
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
Возможный дубликат:
Как определить, является ли файл нормальным файлом или каталогом с помощью python
Как вы проверяете, является ли путь каталогом или файлом в python?
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
использовать os.path.isdir(path)
подробнее здесь http://docs.python.org/library/os.path.html
Многие из функций каталога Python находятся в os.path
module.
import os
os.path.isdir(d)
Образовательный пример из stat:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)