我必须从这段代码中获取图形,但似乎有些东西无法使用它。
当我运行代码时,我得到了这个:
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
答案 0 :(得分:3)
您的问题是您正在读取第一个for linea in readFile
循环中输入文件的每一行。当您尝试再次读取内容时,您将只获得一个空字符串。要么取消第一个for循环,要么在行readFile.seek(0)
sepFile = readFile.read().split("\n")
您的计划的工作版本将是
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'