How do I divide the content of a txt file by /2 in Python without encountering 'ValueError: invalid literal for int() with base 10'?

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

How do I divide the content of a txt file by /2 in Python without encountering 'ValueError: invalid literal for int() with base 10'?

问题

我正在编写一个可以从一个txt文件中用/2进行除法的程序,使用Python。

所以在这段代码中,op将读取txt文件的内容:

with open("python/file/t.txt") as txt:
    op = txt.read()
   
    def div():
        divide = int(op)/2
        print(divide)
div()

但是它显示了一个错误:

ValueError: invalid literal for int() with base 10: '1\n2\n3\n4\n5\n6\n7\n8\n9\n10'

我的t.txt文件中是1到10垂直排列的。

英文:

I am writing a program that can divide with /2 from a txt file python

So in this code op will read the content of txt

with open("python/file/t.txt") as txt:
    op = txt.read()
   
    def div():
        divide = int(op)/2
        print(divide)
div()

But it is showing me a error:

ValueError: invalid literal for int() with base 10: '1\n2\n3\n4\n5\n6\n7\n8\n9\n10'

My t.txt file has 1 to 10 arranged vertically.

答案1

得分: 3

当你调用 read() 时,你会得到文件的整个内容,包括数字的文本和换行符。要处理每个数字(每行一个),你可以使用换行符 "\n" 来拆分 op。示例如下:

with open("in.txt", "r") as file_in:
    for row in file_in.read().split("\n"):
        print(int(row) / 2)        

请注意,split() 也是有效的,因为默认行为是在空白字符(包括换行符和制表符)上进行拆分。

然而,Python 允许你简化这个过程,如下所示:

with open("in.txt", "r") as file_in:
    for row in file_in:
        print(int(row) / 2)

无论哪种方法,都会得到以下结果:

0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0

附加说明:

根据提问者的意见,使用 readlines() 也可以实现相同的效果,我将他们的评论整合到这个答案中以增加清晰度。

with open("in.txt") as file_in:
    for row in file_in.readlines():
        print(int(row) / 2)        
英文:

When you call read() you are getting back the entire contents of the file. The text of the numbers and the newline characters. To process each number (one per line) you would want to split op on the newline character "\n".

Something like:

with open("in.txt", "r") as file_in:
    for row in file_in.read().split("\n"):
        print(int(row) / 2)        

Note that split() would also be valid as the default behavior is split() to do so on whitespace including line breaks and tabs.

However, this is such a common thing python allows one to simplify this to:

with open("in.txt", "r") as file_in:
    for row in file_in:
        print(int(row) / 2)

Either will give you back:

0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0

Addendum:

Per the OP, the use of readlines() also fits the bill here and I will pull their comment into this answer for clarity.

with open("in.txt") as file_in:
    for row in file_in.readlines():
        print(int(row) / 2)        

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

发表评论

匿名网友

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

确定