itsource

파일이 python에서 디렉토리인지 일반 파일인지 확인하는 방법

mycopycode 2022. 12. 24. 17:28
반응형

파일이 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 디렉토리 함수의 대부분은 모듈에 포함되어 있습니다.

import os
os.path.isdir(d)

통계 문서의 교육용 예:

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's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's 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)

언급URL : https://stackoverflow.com/questions/3204782/how-to-check-if-a-file-is-a-directory-or-regular-file-in-python

반응형