pseudoepinephrine
pseudoepinephrine

Reputation: 141

Unsupported Operand Type(s) ; Python3

I'm trying to create a counter that saves the amount of key-presses to a text file.

This is the code atm.

import keyboard

count = open("count.txt", "w+")
amount = count 


while True:  
   if keyboard.is_pressed('space'):  # if key 'q' is pressed
       print("This idiot has pressed the spacebar " +
                         str(amount) + " times!")
       amount = amount + 1
       count.write(amount)

Which returns this error;

TypeError: unsupported operand type(s) for +: '_io.TextIOWrapper' and 'int'

I think I understand why I'm getting this error, but I want a second opinion.

What I think is happening, is that the .txt isn't using the right encoding; e.g UTF-8.

Upvotes: 1

Views: 362

Answers (1)

Vishakha Lall
Vishakha Lall

Reputation: 1314

count is a TextIOWrapper object, if you want to read the contents, you should read() the file.

import keyboard

count = open("count.txt", "w+")
amount = count.read() 


while True:  
   if keyboard.is_pressed('space'):  # if key 'q' is pressed
       print("This idiot has pressed the spacebar " +
                         str(amount) + " times!")
       amount = int(amount) + 1
       count.write(amount)

Upvotes: 2

Related Questions