Answer the question
In order to leave comments, you need to log in
How to display to the user that he entered the wrong filename in python?
The program prompts the user for a file name. How to make it write that you made a mistake if the user entered the wrong file name.
Now there is such a small code, you just need to add it in case you enter the wrong file:
filename = input("Введите имя файла: ")
file_object = open(filename, 'r')
all_the_text = file_object.read( ).split('\n')
print (all_the_text)
num_words = 0
with open(filename,'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Число слов:")
print(num_words)
Answer the question
In order to leave comments, you need to log in
To be honest, I did not really understand what you need :D
The following code checks for the existence of a file and displays an error if it does not exist.
# -*- coding: utf-8 -*-
try:
file_object = open(filename, 'r')
except IOError as e:
print('Неверное имя файла.')
Continuation
try:
filename = input("Введите имя файла: ")
file_object = open(filename + ".txt", 'r')
all_the_text = file_object.read( ).split('\n')
print (all_the_text)
num_words = 0
with open(filename + ".txt",'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Число слов:")
print(num_words)
except IOError as error:
print(error)
print("Файл не найден.")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question