我是python& amp;的初学者我的作业任务结构有些问题;我的任务是:"编写一个程序,询问用户文件名,打开文件并读取文件一次,然后向用户报告字符数(包括空格和行尾字符),单词数和文件中的行数。
如果用户输入的文件名不存在,那么您的程序应该根据需要为她提供尽可能多的尝试以输入有效的文件名。从用户获取有效的文件名是一种常见的操作,因此首先编写一个单独的,可重复使用的函数,该函数会反复询问用户文件名,直到她输入您的程序能够打开的文件为止。" 而且,我并没有这样开始(现在我想知道我是否按照"用/和#34进行结构化的方式,那就是'方式甚至做到这一点,但我现在的问题是在错误被抛出后让它回到代码的try部分(我错过了解释这个问题的课程,所以我只读过这个,所以我知道我和#39;我没做正确的事情。。只要它存在文件名,我就能让它工作,如果不是,它就不会在屏幕上打印任何内容。这是我的代码:
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
答案 0 :(得分:1)
我会重新组织此代码,以便在循环中打开文件。无论用户输入无效文件名多少次,代码都会请求新的文件名,然后重试。
lineCount = 0
wordCount = 0
charCount = 0
f = None
while f is None:
filename = input("please enter a file name to process:")
try:
f = open(filename)
except OSError:
print("That file doesn't exist")
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)
答案 1 :(得分:-1)
写一个无限循环while True
。如果文件名正确,请在try
的末尾添加break
。
很高兴帮助