About the input() function

When I execute the code down below in the Sublime text editor, the input() doesn’t work. I mean when I input a text and press the enter button, it doesn’t execute the code, rather it just goes to the next line.
Can someone tell me what the problem is?

# counting the words in a file and finding the most frequent word
name = input('Enter file: ')
handle = open(name)

counts = dict()
for line in handle:
	words = line.split()
	for word in words:
		counts[word] = counts.get(word, 0) + 1

bigcount = None
bigword = None
for word,count in counts.items():
	if bigcount is None or count > bigcount:
		bigword = word
		bigcount = count

print(bigword, bigcount)

After you open the file, read from the file and store it in a variable. It’s that variable you’ll use in place of the handle variable.

Also, remember to close your file. A better option is to use the “with” block to open your file so it closes by itself.

Here is what the beginning of your code might look like using the “with” block to open your file:

name = input('Enter file: ')
with open(name, mode="r", encoding="utf-8") as name:
    handle = name.read()

It works well this way.

It’s still the same issue I’m facing. I think there’s some systematic problem why my codes not working. But I can’t figure out what it is :frowning_face_with_open_mouth:

1 Like

Does it print anything at all?

It just prints the input text Enter file: . But when I type something as an input and press the enter button, instead of executing the next codes it just goes to the next line in output panel.

I’ve went and tried it myself in the sublime. Looks like it needs some additional actions to allow input work as expected. See Build broken? - Python 3 - input() - Technical Support - Sublime Forum


I think it’s because it’s in the Sublime text editor. I ran the code in VS Code and it gave the right output - the most frequent word and the number of times it occurred.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.