Search code examples
pythoncastingtype-conversioninteger

invalid literal for int() with base 10: when try to convert a string literal


I am trying to read text from a file and then go through the characters in the string one by one and convert those to numbers and do some arithmetic operations after that. I have not included the arithmetic operation part in the code provided here. I tried accessing the type of the fo.read(c) line before the loop and it gave me the type as a string. But when I tried to convert it to an integer it gave me the error line 9, in <module> num = int(text)ValueError: invalid literal for int() with base 10: ''

I ensured the characters I included in the text file were numbers.

Below is the code I tried.

fn = 0
fo=open("SSS.txt",'r')
c = 0
num = 0

while c < 10:
    text = fo.read(c)
    print(text)
    num = int(text)
    fo.close()

Solution

  • When you print the value of fo.read(c) when c=0, the output is "" which is an empty string; and cannot be converted to a number. Hence, it must be skipped to ensure this error does not occur. The same case needs to be considered when the end of file has been reached but your loop is still running.

    Another problem with your code is that you are not updating the value of c which is going to become an infinite loop. I have corrected your answer by taking some reference from here.

    with open("SSS.txt",'r') as fo:
        c = 1    
    
        while c<10:
    
            text = fo.read(1)
    
            """ Checking if text is an empty string,
            the case where your loop is still running but\
            the end of file has been reached."""
    
            if text != "":
                num = int(text)
                print(text)
    
            # Updating the value of c.
            c+=1
    

    Note - "It is good practice to use the "with" keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point." as per the official documentation.

    Also, the read() function takes size as an input parameter, which denotes the number of characters to be read. It has been kept as 1 to read the file character by character.