M
M
molly_dolly2018-05-23 23:48:31
Python
molly_dolly, 2018-05-23 23:48:31

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)

I don't understand what to do at all

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly, 2018-05-23
@molly_dolly

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('Неверное имя файла.')

A
Alexander, 2018-05-24
@sanya84

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 question

Ask a Question

731 491 924 answers to any question