我有一个简单的函数,用于将文本文件的内容读入Python变量。我用它来导入SQL查询。该函数接受一个参数,即文本文件的路径和名称,并允许多次尝试正确地获取名称,从而允许键入错误或拼写错误。默认情况下,此参数设置为“无”。如果找不到该文件,函数将打印一条错误消息并显示一个input()框,以允许输入新的路径和文件名。然后,该函数要么返回字符串(表示SQL查询),要么在找不到文件时返回None。在
其功能是:
def readQueryFromFile(queryPathAndFileName = None):
maxAttempts = 3
for i in range(maxAttempts):
if (queryPathAndFileName is None) or (i > 0):
queryPathAndFileName = input("Enter path and filename for text file contains SQL query: ")
try:
tempFileObject = open(queryPathAndFileName)
tempQuery = tempFileObject.read()
tempFileObject.close()
break
except FileNotFoundError as e:
print("\nA FileNotFoundError occurred.\nError number {0}: {1}. File named \'{2}\' does not exist at that location.".format(e.args[0],e.args[1],queryPathAndFileName))
if i < (maxAttempts-1):
print('\nPlease re-enter path and filename details.\n') # Only say 'Please try again' if not last attempt.
else:
# If query file can't be found then set tempQuery to None
print('\nFailed to find file containing query after {0} attempts.\n'.format(i+1))
tempQuery = None
return tempQuery
可以使用以下方法在Jupyter笔记本单元中调用函数:
^{pr2}$显然,路径和文件名是没有意义的,函数会显示错误消息并提示再次输入路径和文件名。但是,错误消息会在输入框显示后显示,如下所示:
Enter path and filename for text file contains SQL query: |________|
A FileNotFoundError occurred.
Error number 2: No such file or directory. File named '/geosgnasoeg/asgogeso.sges' does not exist at that location.
Please re-enter path and filename details.
消息出现顺序混乱可能会令人困惑。有趣的是,如果输入了第二个不正确的路径和文件名,则输出会正确地重新排列自己。在
我使用的是一款运行ElCapitan的Mac电脑,这个问题在Safari和Firefox中都会出现。在
有没有一种方法可以强制显示在Jupyter笔记本中的输出以正确的(即顺序)顺序出现?在
目前没有回答
相关问题 更多 >
编程相关推荐