2

我必须从这段代码中得到一个图形,但似乎有些东西不能用它。

当我运行代码时,我得到了这个:

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 
4

1 回答 1

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'
于 2013-07-08T21:23:20.717 回答