我试图根据用户输入将图像保存到目录中。例如:
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()以便查看我的窗口,那么循环会出现问题而且我无法获得输入。我不想手动解析此文件夹。
注意我现在才学习Python。
答案 0 :(得分:1)
处理路径和目录时,应使用os.path模块。 (这不是必需的,但它更容易处理路径)。即使目录和路径约定看起来不同,这个模块也可以更轻松地制作可在Windows和Linux上运行的跨平台代码。下面是选择目录并写入目录的一个小例子。
此示例有一个while循环,只要输入不是'e',就会不断地请求输入。用户可以写入目录a或目录b。从这里我们使用os.path.join()附加目录和随机文件名。请注意,我没有使用unix样式的路径或Windows样式的路径。如果要在本地运行,只需确保创建目录“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