我想將數據保存在文本文件中,並從這些文件創建字典,稍後將傳遞給函數。Python:需要幫助從文本文件創建字典並拆分列表
這裏是我的代碼:
def lesson_dictionary(filename):
print "Reading file ", filename
with open(filename) as f:
mylist = f.read().strip().split()
dictionary = OrderedDict(zip(mylist[::2], mylist[1::2])) #keep keys/values in same order as declared in mylist
print dictionary
return dictionary
隨着爲sample.txt包含用空格隔開,它工作正常的鍵/值對的兩列的樣本文件。例如,
AB
CD
EF
產生像這樣的列表:
OrderedDict([('a', 'b'), ('c', 'd'), ('e', 'f')])
,但如果我更改代碼和.txt文件的內容,它打破了。例如,如果包括sample2.txt:
A:B
C:d
Ê:F
和我的代碼是
def lesson_dictionary(filename):
print "Reading file ", filename
with open(filename) as f:
mylist = f.read().strip().split(':') #CHANGED: split string at colon!
dictionary = OrderedDict(zip(mylist[::2], mylist[1::2]))
print dictionary
return dictionary
我得到以下輸出:
OrderedDict([('a', 'b \nc'), ('d\ne', 'f')])
發生了什麼?爲什麼strip()爲第一個.txt文件而不是第二個?預先感謝您的幫助。
我真的建議的替代標記表明「......除了一次讀取文件的一行。」讓文件對象分割線,例如f'中的行將更具可讀性。 – Leovt
感謝您的意見,@Leovt。 – user1186742
這工作完美!非常感謝你的解釋和示例代碼,馬克。 – user1186742