尝试编写python代码,询问用户输入文件的名称,它可以工作,但是当我输入输入文件时,它表示“输入文件”没有定义?

时间:2015-02-13 10:39:02

标签: python user-input

这是我的代码,第4-6行要求输入文件:

import numpy as np
from matplotlib import pyplot as plt

infile = input('Enter input file name:') 
mags = open( infile ,'r')
cluster = input('Enter the name of the cluster:')

vmag=[]
imag=[]

for line in mags:
    column = line.split()
    flag=int(float(column[0]))
    RA=(column[14])
    DEC=(column[15])
    RA = int(float(RA.split(':')[2]))
    DEC = int(float(DEC.split(':')[2]))

    a = input('Enter flag lower range value')
    b = input('Enter flag higher range value')    
    c = input('Enter RA lower range value:')
    d = input('Enter RA higher range value:')
    e = input('Enter DEC lower range value:')
    f = input('Enter DEC higher range value:')

    if flag in range (a,b):
    #if flag == 0:
        if RA in range (c,d):

             if DEC in range (e,f):

                vmag.append(float(column[1]))
                imag.append(float(column[4]))   

vmag = np.array(vmag)
imag = np.array(imag)


plt.scatter(vmag-imag, vmag, lw=0, s=5)
plt.ylim(27, 21)
plt.xlim(-0.5, 3.0)
plt.title('Colour Magnitude Diagram', cluster)
plt.ylabel('F555 mag')
plt.xlabel('F555-F814')
plt.grid(b=True)
plt.savefig(cluster, '.pdf')
plt.show()

但是当我运行它并输入输入文件'ngc185_u3kl01.txt'(位于同一目录中)时,我收到以下错误:

Enter input file name:ngc185_u3kl01
Traceback (most recent call last):

  File "<ipython-input-2-917781cbe168>", line 1, in <module>
    runfile('C:/Users/Keith/.spyder2/CMD.py', wdir='C:/Users/Keith/.spyder2')

  File "C:\Users\Keith\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile
    execfile(filename, namespace)

  File "C:/Users/Keith/.spyder2/CMD.py", line 5, in <module>
    infile = input('Enter input file name:')

  File "C:\Users\Keith\Anaconda\lib\site-packages\IPython\kernel\zmq\ipkernel.py", line 364, in <lambda>
    input = lambda prompt='': eval(raw_input(prompt))

  File "<string>", line 1, in <module>

NameError: name 'ngc185_u3kl01' is not defined

我已经检查并仔细检查了文件名与我输入的内容相匹配,甚至复制并粘贴了输入文件名但仍未成功。我也在最后一次尝试使用'.txt'。

2 个答案:

答案 0 :(得分:1)

在Python 2上,您应该使用raw_input,而不是inputinput将结果计算为数字或字符串,并且被认为是危险的和unpythonic,因为如果用户输入了不好的内容,例如不带引号的字符串或者什么都没有,则必须捕获异常。

input真的只是古老而陈词滥调。这就是他们在Python 3中改变它的原因。

答案 1 :(得分:1)

或者你可以保持&#34;输入&#34;函数并使用Python 3.x解释器。