2012-07-28 33 views
-1

我試圖從 我的文件wahbilogintest.py(其中包含字典kids{})獲得密鑰和值時遇到問題。不能從字典中獲取鍵和值在目錄中

你能幫我一下,我將如何搜索我的文件wahbilogintest.pyC:/webbplats/mydata目錄下,然後在文件中迭代以獲取/攜帶密鑰和值?

我的源代碼

class visafilerIkatalogen : 
    import os 
    folder = 'c:/webbplats/mydata/' 
    dinfil = raw_input("Enter your userprofile med prefix.txt: ") 
    #dindictionary = raw_input("Enter your dictionary name: ") 
    loginReadProfile = open(folder+str(dinfil),'r') 
    for key, value in dinfil.iteritems(): 
      print 'Username is: ',key 
      print 'value is: ',value 

    print loginReadProfile.readlines() 
    loginReadProfile.close() 


Myobj12 = visafilerIkatalogen() 

回答

0

打開一個文件open()給你一個iterable這將產生對文件中的每一行的字符串。它確實爲而不是給你一個對象,你可以在這個對象上調用.iteritems()

要訪問文件中的python對象,你需要import它,不要打開它。要做到這一點給你的用戶輸入的方法之一是:

import os 
import sys 

folder = 'c:/webbplats/mydata/' 
dinfil = raw_input("Enter userprofile med prefix") 
## Get the full path, the directory, and the filename 
full_path = path.join(folder, dinfil) 
path, filename = os.path.split(full_path) 
filename, ext = os.path.splitext(filename) 
## Add the directory to the sys.path and import the module 
sys.path.append(path) 
data_module = __import__(filename) 

在這一點上,你必須一個python module的參考。您可以使用虛線符號訪問此模塊中定義的名稱。所以,如果有一個名爲「孩子的字典,你可以遍歷它的鍵/值對這樣的:

for key, value in data_module.kids.iteritems(): 
    print 'Username is: %s' % key 
    print 'Value is %s': % value 

你應該認真考慮這種方法來訪問每個用戶的數據。它過於複雜。有可能有很多更好的方法來做到這一點,但沒有關於你想要實現的更多信息,我無法真正幫助更多。

也有幾件事情可以做,以提高你的代碼:

  1. 你的類應該繼承object
  2. import語句應(幾乎)總是類定義
  3. 使用sys.path.join()外連接部分文件路徑
+0

我得到了TypeError:join()只需要一個參數(給出2),並試圖修復,但它不起作用。 – user1559435 2012-07-29 10:22:45