sys.argv:索引超出范围

时间:2017-02-14 08:04:59

标签: python-2.7 numpy pycharm sys

我尝试运行此代码

import sys
import numpy as np
filename = sys.argv[1]
X = []
y = []
with open(filename, 'r') as f: 
     for line in f.readlines():
        xt, yt = [float(i) for i in line.split(',')]
        X.append(xt)
        y.append(yt)

我收到此错误

4 filename = sys.argv[1]   
  5 X = []   
  6 y = []  
IndexError: list index out of range  

我该如何解决?

我在txt中有一个文件,我想从中读取数据。

4.94,4.37
-1.58,1.7
-4.45,1.88
-6.06,0.56
-1.22,2.23
-3.55,1.53
0.36,2.99
-3.24,0.48
1.31,2.76
2.17,3.99
2.94,3.25
-0.92,2.27
-0.91,2.0
1.24,4.75
1.56,3.52
-4.14,1.39
3.75,4.9
4.15,4.44
0.33,2.72
3.41,4.59
2.27,5.3
2.6,3.43
1.06,2.53
1.04,3.69
2.74,3.1
-0.71,2.72
-2.75,2.82
0.55,3.53
-3.45,1.77
1.09,4.61
2.47,4.24
-6.35,1.0
1.83,3.84
-0.68,2.42
-3.83,0.67
-2.03,1.07
3.13,3.19
0.92,4.21
4.02,5.24
3.89,3.94
-1.81,2.85
3.94,4.86
-2.0,1.31
0.54,3.99
0.78,2.92
2.15,4.72
2.55,3.83
-0.63,2.58
1.06,2.89
-0.36,1.99

1 个答案:

答案 0 :(得分:0)

确保以@hpaulj建议传递文件名。您还可以检查sys.argv的长度

import sys
print(sys.argv, len(sys.argv))
if len(sys.argv) < 2:
   sys.exit('Usage: %s input_file' % sys.argv[0])

您可能还想检查此帮助程序类: https://docs.python.org/2/library/fileinput.html#module-fileinput