gpt4 book ai didi

python - 如何在 python 中将文件行转换为 float/int

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:15 27 4
gpt4 key购买 nike

每当我尝试运行这段代码时:

    #Open file
f = open("i.txt", "r")
line = 1

#Detect start point
def findstart( x ):
length = 0
epsilon = 7
a = 3
line_value = int(f.readline(x))
if line_value == a:
length = length + 1
x = x + 1
findend(x)
elif line_value == epsilon:
x = x + 2
findstart(x)
else:
x = x + 1
findstart(x)

#Detect end point
def findend(x):
line_value = int(f.readline(x))
if line_value == a:
length = length + 1
return ("Accept", length)
elif line_value == epsilon:
x = x + 2
length = length + 2
findend(x)
else:
x = x + 1
length = length + 1
findend(x)

findstart(line)

我得到这个错误代码:

    Traceback (most recent call last):
File "C:\Users\Brandon\Desktop\DetectSequences.py", line 39, in <module>
findstart(line)
File "C:\Users\Brandon\Desktop\DetectSequences.py", line 16, in findstart
findend(x)
File "C:\Users\Brandon\Desktop\DetectSequences.py", line 26, in findend
line_value = int(f.readline(x))
ValueError: invalid literal for int() with base 10: ''

谁能帮我找出问题所在?在我看来,它正在尝试读取一个空单元格,但我不知道为什么会这样。我正在扫描的文件目前只有两行,每行都是“3”,所以它应该输出成功,但我无法克服这个错误。

最佳答案

我不确定您的代码,但错误消息表明您的文件中有一个空行,您正在尝试将其转换为 int。例如,很多文本文件最后都有一个空行。

我建议在转换之前先检查您的线路:

line = ...
line = line.strip() # strip whitespace
if line: # only go on if the line was not blank
line_value = int(line)

关于python - 如何在 python 中将文件行转换为 float/int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7974269/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com