2014-10-20 54 views
-1

我想獲取一個文本字符串,並寫入一個文件,如果該文件不存在。這是目前的代碼。存儲鍵盤輸入變量作爲字符串

#!/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 
+0

什麼是你的Python版本?在終端上執行'python --version'! – Kasramvd 2014-10-20 07:51:54

回答

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'