无法将字符串文字转换为整数(使用基数10):尝试转换字符串文字时。

huangapple go评论80阅读模式
英文:

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

问题

我正在尝试从文件中读取文本,然后逐个遍历字符串中的字符,将它们转换为数字,并在之后进行一些算术操作。我没有在此处提供代码的算术操作部分。我尝试在循环之前访问fo.read(c)行的类型,它给了我一个字符串类型。

但是,当我尝试将它转换为整数时,它给了我一个错误信息 line 9, in <module> num = int(text)ValueError: invalid literal for int() with base 10: ''

我确保在文本文件中包含的字符是数字。

以下是我尝试的代码:

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()

注意:请检查代码的逻辑,因为在循环中关闭文件可能不是您想要的行为。如果需要在循环中多次读取文件,请将fo.close()移动到循环之外。

英文:

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 &lt;module&gt; num = int(text)ValueError: invalid literal for int() with base 10: &#39;&#39;

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

Below is the code I tried.

fn = 0
fo=open(&quot;SSS.txt&quot;,&#39;r&#39;)
c = 0
num = 0

while c &lt; 10:
    text = fo.read(c)
    print(text)
    num = int(text)
    fo.close()

答案1

得分: 1

当您在c=0时打印*fo.read(c)*的值时,输出为空字符串"",它不能转换为数字。因此,必须跳过它,以确保不会发生此错误。当文件已经到达结尾但您的循环仍在运行时,需要考虑相同的情况。

您的代码的另一个问题是,您没有更新c的值,这将导致无限循环。我已经根据这里进行了修正。

with open("SSS.txt", 'r') as fo:
    c = 1    

    while c < 10:

        text = fo.read(1)
    
        """ 检查text是否为空字符串,
        这是您的循环仍在运行但已经到达文件结尾的情况。"""

        if text != "":
            num = int(text)
            print(text)
    
        # 更新c的值。
        c += 1

注意 - 处理文件对象时使用**"with"**关键字是一种良好的做法。其优点是,即使在某个时刻引发异常,文件也会在其套件完成后正确关闭,根据官方文档

另外,read()函数接受size作为输入参数,表示要读取的字符数。它已设置为1**,以逐个字符读取文件。

英文:

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(&quot;SSS.txt&quot;,&#39;r&#39;) as fo:
    c = 1    

    while c&lt;10:

        text = fo.read(1)

        &quot;&quot;&quot; Checking if text is an empty string,
        the case where your loop is still running but\
        the end of file has been reached.&quot;&quot;&quot;

        if text != &quot;&quot;:
            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.

答案2

得分: 1

以下是翻译好的代码部分:

with open("SSS.txt", 'r') as fo:
    c = 1
    num = 0
    myall = fo.read()
    print(myall)
    num = int(len(myall))
    print(num)
    fo.seek(0)
    while c <= num:
        txt = fo.read(1)
        if(txt != ""):
            newtxt = int(txt)
            print(newtxt)
                    
        c += 1 

fo.close()
英文:

You can improve the previous answer like in the below code.

with open(&quot;SSS.txt&quot;,&#39;r&#39;) as fo:
    c = 1
    num = 0
    myall = fo.read()
    print(myall)
    num = int(len(myall))
    print(num)
    fo.seek(0)
    while c &lt;= num:
        txt = fo.read(1)
        if(txt != &quot;&quot;):
            newtxt = int(txt)
            print(newtxt)
                    
        c+=1 

fo.close()

huangapple
  • 本文由 发表于 2023年7月6日 12:03:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定