将键盘输入存储在变量字符串中

时间:2014-10-20 07:50:28

标签: python

如果文件不存在,我正在尝试获取一串文本并将其写入文件。这是迄今为止的代码。

#!/usr/bin/python

import os.path as path

configFileLocation = "~/.sajan.io-client"

def createConfig():
    print "Creating config file\n"
    apikey = input("Enter the API key: ")
    configFile = open(configFileLocation, "w")
    configFile.write(apikey)
    configFile.close()

if path.isfile(configFileLocation) == False:
    createConfig()

运行时,我会收到Enter the API key:的提示,而我输入的内容似乎不会被用作字符串。这是我得到的输出,我无法理解它。这几乎就像Python试图将我输入的内容用作脚本中的变量。

创建配置文件

Enter the API key: somerandomapikey123
Traceback (most recent call last):
  File "./new-thought.py", line 15, in <module>
    createConfig()
  File "./new-thought.py", line 9, in createConfig
    apikey = input("Enter the API key: ")
  File "<string>", line 1, in <module>
NameError: name 'somerandomapikey123' is not defined

1 个答案:

答案 0 :(得分:0)

您使用的是Python2,请使用raw_input代替inputraw_input将确保输入存储为字符串:

Python 2.7.3 (default, Jan  2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> result = input('Hello: ')
Hello: world
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'world' is not defined
>>> result = raw_input('Hello: ')
Hello: world
>>> result
'world'