2017-09-21 3 views
1

사용자 입력을 기반으로 디렉토리에 이미지를 저장하려고했습니다. 예 :Python이 사용자 입력에 따라 특정 디렉토리에 저장

if user enters 'A' 
    save in A folder 
elif user enters 'B' 
    save in B folder 

등등.

이 두 가지 일이 발생하면 폴더가 채워지지 않고 내 루프가 두 개가됩니다. getch() 및 input()을 사용하여 잠시 동안 노력했지만 둘 다 단순히 나를 위해 작동하지 않습니다.

여기 내 코드입니다.

getInput = input("Enter Which Window to Save") 

if getInput == int('1'): 

    cardFound = input("Which Card was Found: ") 
    cardsFound.append(cardFound) 

    print("\tFlop Cards Found") 
    print(cardsfound) 
    print (52 - counter1,"Left to find...") 
    cv2.imwrite("C:/FlopOne/" + cardFound + ".jpg") 

cv2.waitKey(0) 

이 이후의 elif 문 모든 getInput에 응답하지만 루프가 getInput에 일시 정지됩니다 때 많이 있습니다. 내 창문 (그중 다섯 개가있다)은 회색 스크린을 그다지 올려 놓지 않는다. 그러나 waitKey()를 호출하여 내 윈도우를 볼 경우 루프 haults와 나는 입력을 얻을 수 없다. 이 폴더를 수동으로 구문 분석하지 않아도됩니다.

참고 지금은 파이썬 만 배우고 있습니다.

답변

1

경로 및 디렉토리를 처리 할 때 os.path 모듈을 사용해야합니다. (필수는 아니지만 경로를 훨씬 쉽게 처리 할 수 ​​있습니다.) 이 모듈을 사용하면 디렉토리와 경로 규칙이 다르게 보일지라도 Windows와 Linux에서 모두 실행되는 크로스 platorm 코드를 만드는 것이 더 쉽습니다. 아래는 디렉토리 선택과 글쓰기에 대한 약간의 예입니다.

이 예제에는 입력이 'e'가 아닌 한 지속적으로 입력을 요청하는 while 루프가 있습니다. 사용자는 디렉토리 a 또는 디렉토리 b에 쓸 수 있습니다. 여기서 우리는 os.path.join()을 사용하여 디렉토리와 랜덤 파일 이름을 추가합니다. 유닉스 스타일의 패스 나 윈도우 스타일의 패스를 사용하지 않는다. 로컬로 실행하려면 디렉토리 "a"와 디렉토리 "b"를 작성하십시오.

import os 
from random import randint 


if __name__ == '__main__': 

    # This is the current working directory... 
    base_path = os.getcwd() 

    while True: 
     # whitelist of directories... 
     dirs = ["a", "b"] 

     # Asking the user for the directory... 
     raw_input = input("Enter directory (a, b): ") 

     # Checking to be sure that the directory they entered is valid... 
     if raw_input in dirs: 

      # Generating a random filename that we will create and write to... 
      file_name = "{0}.txt".format(randint(0, 1000000)) 

      # Here we are joining the base_path with the user-entered 
      # directory and the randomly generated filename... 
      new_file_path = os.path.join(base_path, raw_input, file_name) 

      print("Writing to: {0}".format(new_file_path)) 

      # Writing to that randomly generated file_name/path... 
      with open(new_file_path, 'w+') as out_file: 
       out_file.write("Cool!") 

     elif raw_input == 'e': 
      break 
+0

감사합니다 카일이 나를 위해 일했습니다 –

+0

K * 실 거예요 ... –

관련 문제