后,我感到有一些问题,我的家庭作业的结构蟒蛇&初学者如何让我的Python代码走回到环路;我的任务是:“编写一个程序,要求用户输入文件名,打开文件并读取文件一次,然后向用户报告字符数(包括空格和行尾字符),字数,以及文件中的行数抛出异常
如果用户输入了一个不存在的文件的名称,那么程序应该给她尽可能多的尝试,以便输入一个有效的文件名。来自用户的有效文件名是一种常用操作,因此首先编写一个单独的可重复使用的函数,该函数会重复询问用户的文件名,直到她键入文件中的程序能够打开。 而且,我也没有启动方式(&现在我想知道如果用我的方式已经与它的结构“与/为”,有一个办法,甚至这样做,但现在我的问题越来越它去在抛出错误后回到代码的try部分(我错过了解释这个的类,所以我只读过这个,所以我知道我没有做正确的事情)。我可以让它工作很长时间因为它的存在,如果它不是一个文件名,不打印输出到屏幕下面是我的代码:
filename = input("please enter a file name to process:")
lineCount = 0
wordCount = 0
charCount = 0
try:
with open(filename, 'r') as file:
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
except OSError:
print("That file doesn't exist")
filename = input("please enter a file name to process:")
而且,我不知道我该怎么做 - 我是否应该放弃了这个整体思路简单的尝试:开放(文件名,“R”)/除外:它的功能= F有反正挽救这个
所以,我认为解决这个问题是这样的:
def inputAndRead():
"""prompts user for input, reads file & throws exception"""
filename = None
while (filename is None):
inputFilename = input("please enter a file name to process")
try:
filename = inputFilename
open(filename, 'r')
except OSError:
print("That file doesn't exist")
return filename
inputAndRead()
lineCount = 0
wordCount = 0
charCount = 0
with open(filename, 'r') as file:
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
但是,我发现了错误:NameError: name 'file' is not defined
您需要一个外部'while'循环,以便在失败时重复代码。见http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – roganjosh
可能的复制[如何使迭代中的脚本等到互联网连接重建?(http://stackoverflow.com/questions/42344303/how-to-make-a-script-wait-within-an-iteration-until-the-internet-connection-is-r) –
为什么不使用os.path.exists()来检查文件是否存在,而不是依赖open所抛出的异常。 –