Home > Software design >  TypeError: 'str' object cannot be interpreted as an integer when opening a file
TypeError: 'str' object cannot be interpreted as an integer when opening a file

Time:10-03

i have the next code

import requests, os, sys
from colorama import *
foo = f"{Fore.GREEN}[ ] {Fore.WHITE}"
def subhyp():
    try:
        kukipbcxz = open('lala.txt','a')
        rp = requests.get("example.com")
        jui = str(rp.text)
        print(jui, file = a)
        print(f"\n{foo}Results saved in lala.txt")
        a.close()
    except KeyboardInterrupt:
        pass

print("""
1.- someoption1
2.- someoption2
3.- sometestoption3
""")

a = str(input("Option = "))
if a == "1":
   print("someoption1")
elif a == "2":
   print("someoption2")
elif a == "3":
   subhyp()

When i Execute Code and select sometestoption3 i get the following error in terminal

    a = open("lala.txt",'w')
TypeError: 'str' object cannot be interpreted as an integer

I have tried convert (a) into str with the next code and i got the next output on terminal a = open(str("lala.txt",'w')) Output:

    a = open(str("lala.txt",'w'))
TypeError: decoding str is not supported

i dont know why this happening if someone can provide me a solution i would appreciate it, thanks for read :)

CodePudding user response:

My crystal ball says that from colorama import * (or maybe another import you're not showing us) accidentally overwrites the built-in open with os.open, which would indeed give the error you're quoting.

>>> from os import open
>>> open("foo.txt", "a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>>

Additionally, you're opening the file with the (nonsense) variable name kukipbcxz, but you'd be using file=a, so that won't work either. (Your IDE should highlight kukipbcxz being unused, and a not being assigned. If it doesn't, switch IDEs...)

It's also better to use with with files, so all in all, try:

import requests
from colorama import Fore

foo = f"{Fore.GREEN}[ ] {Fore.WHITE}"


def subhyp():
    try:
        rp = requests.get("example.com")
    except KeyboardInterrupt:
        return
    with open('lala.txt', 'a') as a:
        jui = str(rp.text)
        print(jui, file=a)
        print(f"\n{foo}Results saved in lala.txt")


print("""
1.- someoption1
2.- someoption2
3.- sometestoption3
""")

a = str(input("Option = "))
if a == "1":
    print("someoption1")
elif a == "2":
    print("someoption2")
elif a == "3":
    subhyp()
  • Related