我正在Python3.2中爲一個項目工作,以至於我需要創建一個字典並自動分配從文本文件中讀取的鍵和值。 大部分完成:創建由方法爭論命名的全局變量
def loadDict(file,dictname):
with open(file,"r") as dict_file:
for i in range(sum(1 for line in open(file))):
line = dict_file.readline()
part0,part1 = "", ""
part0 = line.split("\:/")[0][1:(len(line.split("\:/")[0])-1)]
part1 = line.split("\:/")[1][1:(len(line.split("\:/")[1])-1)]
dictname[part0] = part1
dict_file.close()
我可以通過創建一個字典使用它,並分別調用函數:通過獲取正確的結果
test_dictinary = {}
loadDict("my_file","test_dictionary")
print(test_dictionary)
。對我來說問題是:我需要在調用方法之前創建一個空字典。
如果有一種方法可以在該方法中自行創建全局字典,我會發現它。因此,
loadDict("my_file","test_dictionary")
會自動爲我創建字典「test_dictionary」,我可以在其他方法中使用。 我也試過它與fromdict具有相同的結果。 搜索功能在這裏和谷歌沒有給我任何解決方案(除了fromdict至極沒有工作)。
EDIT [社區解決方案]:
def loadDict(file,dictname):
helpdict = {}
with open(file,"r") as dict_file:
for line in dict_file:
part0 = line.split("\:/")[0][1:(len(line.split("\:/")[0])-1)]
part1 = line.split("\:/")[1][1:(len(line.split("\:/")[1])-1)]
helpdict[part0] = part1
globals()[dictname] = helpdict
使用'with'語句打開一個文件的目的是爲了讓'with'處理關閉它。自己關閉是多餘的。 – user2357112
'爲我在範圍內(總和(1爲打開(文件)中的行)):line = dict_file.readline()' - 爲什麼你會那樣做?您再次打開文件,而不關閉它,只是想知道需要讀取多少行。爲什麼不直接在'dict_file'中使用'for line? – user2357112
@ user2357112不完全是原始問題的一部分。當我設置一些東西並在之後清理它時,我傾向於過度複雜化。不好的代碼沒有任何藉口,但你要求的原因。謝謝你幫助我。解決問題並清理代碼。 – Jirajha