gpt4 book ai didi

Python:读取带有负数的文件

转载 作者:行者123 更新时间:2023-12-01 03:11:24 25 4
gpt4 key购买 nike

我试图读取 .txt 文件并将其附加到列表内的列表中,但遇到了这个问题。

ValueError:以 10 为基数的 int() 的文字无效:'-'

其中我的代码是这样的:

def readfiles(filename):
with open(filename) as f:
content = f.readlines()
matrix=[]
tem=[]
for i in range(len(content)):
tem=[]
content[i] = content[i].replace('\n','')
content[i] = content[i].replace(',', '')
for j in range(len(content[i])):
tem.append(int(content[i][j]))
matrix.append(tem)

return matrix

但是如果我将 tem.append(int(content[i][j])) 替换为 tem.append(content[i][j])

列表似乎有所不同,看起来像这样:

[['3', '-', '2', '1'], ['4', '-', '1', '0'], ['0', '2', ' 1']]

我希望我的函数从文件中读取负值。谁能帮忙解决这个问题吗?

我的 .txt 文件如下所示:

3,-2,1
4,-1,0
0,2,1

最佳答案

我猜这会起作用:

def readfiles(filename):
with open(filename) as f:
return [[int(num) for num in line.split(",")] for line in f]

您遇到的问题是您正在迭代您的行(这是一个字符串),这会为您提供单个字符而不是“逗号之间的内容”:

假设当前行 (content[i]) 是 "3,-2,1"。之后:

content[i] = content[i].replace(',', '')

content[i] 现在是“3-21”。它怎么知道你的号码是多少?迭代该字符串会得到 "3", "-", "2", "1",其中 "-" 导致抛出异常。

关于Python:读取带有负数的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873321/

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