2013-07-08 60 views
1

我必須從此代碼獲取圖形,但似乎有些東西不適用於它。ValueError:int()與基數爲10的無效文字:''

當我運行代碼,我得到這個:

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 
+2

是什麼'sepFile'?你至少有一行*不*有整數。 –

+1

嘗試打印出'sepFile',以確保您獲得了您所期望的。它看起來像你期待一個字符串數組,其中每個字符串的形式是「int,int」。如果這些行中的某些行包含空格或其他字符,您可能會遇到問題。 – FrancesKR

回答

3

你的問題是,你正在閱讀的輸入文件中的每行第一個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' 
+0

由於這個答案,我也解決了我的問題;) – Jetse

+0

謝謝你的男人!現在它工作完美! –

相關問題