如何检测用户何时输入作为输入()

时间:2017-08-01 16:21:11

标签: python python-3.x terminal

我正在编写的脚本的一部分涉及获取文件以传递到我的终端应用程序的其他方面。这是我的代码:

def get_file():

custom_data_folder = input("Name of custom data directory - " +
                           "Hit ENTER to use default: ")
file_name = input("File name: ")
default_path = os.path.abspath(os.path.join('data', file_name))
custom_path = os.path.abspath(os.path.join(custom_data_folder, file_name))

if custom_data_folder == '\n':
    return(default_path if os.path.exists(default_path) is True 
                     else "The file or path does not exist.")
else:
    return(custom_path if os.path.exists(custom_path) is True 
                       else "The file or path does not exist.")

我的脚本假定文件位于名为“data”的目录中,但我想提供一个输入文件所在的自定义目录的选项。

当我尝试使用“/ n”换行来检测用户是否输入时,问题出现了。它似乎只是返回工作 - 和目录中的文件而不是“数据”目录及其目标的文件。

如何检测用户是否输入?

我在linux / ubuntu工作。仅针对该平台的解决方案很不错,但如果可能的话,我更愿意使用多平台解决方案。

1 个答案:

答案 0 :(得分:2)

如果用户按下enter而不在输入中键入任何内容,则会返回空字符串。您可以将if语句更改为以下内容。

if custom_data_folder == '':