gpt4 book ai didi

python - 值错误: invalid literal for int() with base 10: ' '

转载 作者:行者123 更新时间:2023-11-30 23:35:07 25 4
gpt4 key购买 nike

我必须从这段代码中获取图形,但似乎有些东西无法使用它。

当我运行代码时,我得到:

ValueError: invalid literal for int() with base 10: ''

这是代码:

import matplotlib.pyplot as plt

x=[]
y=[]

readFile = open("C:/Users/Martinez/Documents/Diego/Python/SampleData.txt","r")

for linea in readFile:
print linea

sepFile = readFile.read().split("\n")
readFile.close()

for plotPair in sepFile:

xAndY = plotPair.split(',')
x.append(int(xAndY[0]))
y.append(int(xAndY[1]))


print x
print y

最佳答案

您的问题是您正在第一个 for linea in readFile 循环中读取输入文件的每一行。当您尝试再次读取内容时,您只会得到一个空字符串。要么消除第一个 for 循环,要么在行 sepFile = readFile.read().split("\n")

之前添加 readFile.seek(0) >

您的程序的工作版本将是

x = []
y = []
with open("C:/Users/Martinez/Documents/Diego/Python/SampleData.txt") as read_file:
for line in read_file:
print line
a, b = line.split(',')
x.append(int(a))
y.append(int(b))

print x
print y

进一步演示该问题:

>>> read_file = open('inp.txt')
>>> for line in read_file: # reads entire contents of file
... print line
...
3,4
5,6
7,8
9,10
>>> read_file.read() # trying to read again gives an empty string
''
>>> out = read_file.read()
>>> int(out) # empty string cannot be converted to an int
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

>>> read_file.seek(0) # moves to beginning of file
>>> read_file.read() # now the content can be read again
'3,4\n5,6\n7,8\n9,10\n'

关于python - 值错误: invalid literal for int() with base 10: ' ' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17535573/

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