programing

디렉토리를 재귀적으로 작성하려면 어떻게 해야 합니까?

coolbiz 2023. 1. 17. 21:50
반응형

디렉토리를 재귀적으로 작성하려면 어떻게 해야 합니까?

디렉토리를 재귀적으로 작성하는 Python 메서드가 있습니까?다음과 같은 경로가 있습니다.

/home/dail/

만들고 싶다

/home/dail/first/second/third

재귀적으로 할 수 있습니까?아니면 디렉토리를 하나씩 작성해야 합니까?

다음 항목도 마찬가지입니다.

chmodchown은 각 파일/dir에 대한 권한을 할당하지 않고 반복적으로 실행할 수 있습니까?

python 3.2부터는 다음을 수행할 수 있습니다.

import os
path = '/home/dail/first/second/third'
os.makedirs(path, exist_ok=True)

플래그 덕분에 (필요에 따라) 디렉토리가 존재해도 불평하지 않습니다.


python 3.4(pathlib 모듈 포함)부터는 다음을 수행할 수 있습니다.

from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)

python 3.5부터 시작하는 것에도 플래그가 있습니다.True디렉토리가 존재하는 경우 예외는 발생하지 않습니다.

path.mkdir(parents=True, exist_ok=True)

os.makedirs 그게 네게 필요한 거야위해서chmod또는chown를 사용해야 합니다.os.walk모든 파일 또는 파일에 직접 사용할 수 있습니다.

os.makedirs를 사용해 보십시오.

import os
import errno

try:
    os.makedirs(<path>)
except OSError as e:
    if errno.EEXIST != e.errno:
        raise

다음은 참조를 위해 구현한 내용입니다.

def _mkdir_recursive(self, path):
    sub_path = os.path.dirname(path)
    if not os.path.exists(sub_path):
        self._mkdir_recursive(sub_path)
    if not os.path.exists(path):
        os.mkdir(path)

도움이 되었으면 좋겠다!

나는 캣 플러스 답변에 동의한다.단, 이 명령어가 Unix와 유사한 OS에서만 사용되는 것을 알고 있는 경우 셸 명령어에 대한 외부 호출을 사용할 수 있습니다.mkdir,chmod,그리고.chown. 디렉토리에 재귀적으로 영향을 미치기 위해 추가 플래그를 전달해야 합니다.

>>> import subprocess
>>> subprocess.check_output(['mkdir', '-p', 'first/second/third']) 
# Equivalent to running 'mkdir -p first/second/third' in a shell (which creates
# parent directories if they do not yet exist).

>>> subprocess.check_output(['chown', '-R', 'dail:users', 'first'])
# Recursively change owner to 'dail' and group to 'users' for 'first' and all of
# its subdirectories.

>>> subprocess.check_output(['chmod', '-R', 'g+w', 'first'])
# Add group write permissions to 'first' and all of its subdirectories.

원래 사용하던 EDITcommands이는 권장되지 않고 주입 공격에 취약하기 때문에 잘못된 선택입니다. (예를 들어 사용자가 다음과 같은 디렉토리를 작성하기 위해 입력을 제공한 경우)first/;rm -rf --no-preserve-root /;모든 디렉토리를 삭제할 수 있습니다).

편집 2 2.7 미만의 Python을 사용하는 경우check_call대신check_output상세한 것에 대하여는, 메뉴얼을 참조해 주세요.

언급URL : https://stackoverflow.com/questions/6004073/how-can-i-create-directories-recursively

반응형