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

2024-09-21 07:55:06 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我尝试运行此代码时:

    #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”,所以它应该输出成功,但我无法通过这个错误。


Tags: inpyreadlinevaluelinelengthusersfile
3条回答

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

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

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

你读的是空行,而python不喜欢这样。你应该检查一下空行。

line_value = f.readline(x).strip()
if len(line_value) > 0:
    line_value = int(line_value)
    ...

变量a、length和epsilon存在范围问题。您可以在findstart中定义它,但尝试在findend中访问它。

另外,传递给readline的变量x并没有做您认为的事情。read line总是返回文件中的下一行,传递给它的变量是一个可选的行长度提示,而不是应该读取哪一行。要对特定行执行操作,请先将整个文件读入列表:

# Read lines from file
with open("i.txt", "r") as f:
    # Read lines and remove newline at the end of each line
    lines = [l.strip() for l in f.readlines()]

    # Remove the blank lines
    lines = filter(lambda l: l, lines)

EPSILON = 7
A = 3
length = 0

#Detect start point
def findstart( x ):
    global length

    length = 0

    line_value = int(lines[x])
    if line_value == A:
        length += 1
        x += 1
        findend(x)
    elif line_value == EPSILON:
        x += 2
        findstart(x)
    else:
        x += 1
        findstart(x)

#Detect end point
def findend(x):
    global length

    line_value = int(lines[x])
    if line_value == A:
        length += 1
        return ("Accept", length)
    elif line_value == EPSILON:
        x += 2
        length += 2
        findend(x)
    else:
        x += 1
        length += 1
        findend(x)

findstart(0)

相关问题 更多 >

    热门问题