Answer:
import os
def search_file(file_name):
file_name += '.txt' # The code automatically adds the .txt extension, so the user is expected to just pass in the name of the file without extension
for _, __, files in os.walk('.'):
for file in files:
if file_name == file:
return file
raise FileNotFoundError('File not found')
file_name = input('Enter the name of the file without extension > ')
file = search_file(file_name)
with open(file) as open_file:
a = open_file.read()
a = a.split()
print('The file {}.txt contain {} words'.format(file_name, len(a)))
Step-by-step explanation:
The above code is written in Python Programming Language. The first line of code is an import statement that imports the os module which is responsible for operating system's functionality in Python. This module is needed because we will be doing things like file search in the code.
The next thing that was done is that a function called search_file which accepts just a single argument was defined. The purpose of this function is to use the os module imported earlier and search for the existence of the file passed in as the argument. If the file is found, the file is returned else a FileNotFoundError is raised
Immediately after the function, the program expects an input from the user which should be the name of the file without the extension. It is also assumed that the filename passed in is a text file with the .txt extension.
After the program gets the file name from the user via the input function, the function we defined earlier is now called passing the value of the input as the argument to the function.
if file passed in does not exist, the program crashes there with the FileNotFound exception - thanks to the raise FileNotFoundError statement in the function.
However if the file exists, the file is opened and read. The contents of the file is splitted by whitespace. Then we use the Python's len function is use to count the items in the list after the split function is ran.
Finally, we print this to the console using string formatting