2015-05-20 115 views
0

假設包含「i = 1」的文本文件,我想閱讀「1」並將其分配給某個變量。所以我怎麼能忽略等號然後檢索號碼?閱讀符號

回答

0

如果文本文件格式化爲python文件,則可以使用exec("file contents")或甚至import該文件。大多數人因爲它的脆弱性而不滿exec():你不知道你正在運行的代碼,除非你自己寫了。

如果你是一個變量放入文件中,那麼我會強烈建議查看pickle。它允許你將python對象和'dump'它們放到一個文件中供以後檢索 - 並且你可以創建一個具有self.i = 1屬性的對象,並且它將在運行中保留。

直接回答你的問題:

#assuming only variables formatted as "variable = value" in file 
#assuming only one variable per line 
variables = { } 
with open("my_variables.txt", "r") as f: 
    #iterates through each line 
    for line in f: 
     #for each line, splits it at the '=' into two parts 
     # and gets first half (before the '=') and strips it of any spaces 
     # before or after it the variable, then stores it as 'name' 
     name = line.split("=")[0].strip() 
     #gets second half and stores it as 'value' the same way 
     value = line.split("=")[1].strip() 
     #if the values are always integers you can convert them 
     # from strings to integers: 
     value = int(value) 
     #stores both variable name and value into the 'variables' dictionary 
     variables[name] = value 
print(variables) # prints { 'i' : '1' }