如何使用 try and except 查看我输入的文件名是否有效?



所以这个文件叫做'data.txt'。我需要编写一个程序来提示用户输入以查看它是否与"data.txt"匹配。例如,如果我输入"数据",它将输出:

Enter name of file:
data
File data not found.

到目前为止,当我输入"数据"时,我的代码:

# Define your functions here
if __name__ == '__main__':
file_name = "data.txt"
# Prompt the user for the name of the file and try opening it for reading
user_input = ''
while user_input in ['data.txt']:
try:
user_input = input('Enter name of file:')
my_file = open('data.txt')
lines = my_file.read()
# Use try-except to catch an error if the file does not exist
except:
print('File data not found.')
# Complete main section of code to read the file, compute the average weight and height, etc.

但是,这将显示(您的程序未生成任何输出(。

关于如何调试我的代码的任何提示?或者我需要修复什么?

您可以使用os.path检查它是否存在,而不是尝试打开文件(并使用广泛的例外子句(。

import os
def ask_file():
while True:
file = input("What is the file?")
if os.path.exists(file):
return file
print("That file does not exist!")

ask_file()

您的 while 循环从未执行过,因为条件始终为 false。您可以尝试以下操作:

if __name__ == '__main__':
try:
user_input = input('Enter name of file: ')
my_file = open(user_input)
lines = my_file.read()
except:
print('File data not found.')

在这里:

try:
f = open('text.txt')
f.close()
except:
print('File not found.')

相关内容

最新更新