2009-08-13 4 views
105

내 프로그램의 출력 정보를 폴더에 넣고 싶습니다. 주어진 폴더가 존재하지 않으면, 프로그램은 프로그램에서 주어진 폴더 이름을 가진 새로운 폴더를 생성해야합니다. 이것이 가능한가? 그렇다면 어떻게 알려주십시오.새 폴더를 만드는 방법은 무엇입니까?

"C:\Program Files\alex"과 같은 폴더 경로가 있고 alex 폴더가 존재하지 않는다고 가정하면 프로그램은 alex 폴더를 만들어야하고 출력 정보를 alex 폴더에 저장해야합니다.

+7

'os' 모듈을 살펴본 결과, 무엇을 찾았습니까? 뭐 유용한거야? 어떤 코드를 시도 했습니까? 아무것도? –

답변

192

당신은 os.makedirs()
의 폴더를 생성하고 이미 존재하는지 os.path.exists()를 사용할 수 있습니다

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath): 
    os.makedirs(newpath) 

당신은 설치 프로그램을 만들려고 노력하는 경우 : Windows Installer 당신을 위해 많은 일을한다.

+8

os.makedirs 호출에서 이중 백 슬래시가 없기 때문에이 작업은 실패합니다. –

+2

그것은 나를 죽이고 있습니다 : newpath = r'C : \ Program Files \ alex '; 그렇지 않으면 os.path.exists (newpath) : os.makedirs (newpath) – hughdbrown

+0

일반적으로 경로 이름은 대소 문자를 구별합니다. – SilentGhost

27

os.mkdir를 사용해 보셨나요?

또한이 작은 코드를 시도 할 수 있습니다 : 필요한 경우

mypath = ... 
if not os.path.isdir(mypath): 
    os.makedirs(mypath) 

makedirs는, 디렉토리의 여러 수준을 만듭니다.

27

os.makedirs은 필요할 경우 중간 디렉터리도 만들 수 있습니다.

import os 

#dir is not keyword 
def makemydir(whatever): 
    try: 
    os.makedirs(whatever) 
    except OSError: 
    pass 
    # let exception propagate if we just can't 
    # cd into the specified directory 
    os.chdir(whatever) 
관련 문제