[]python]python 讀取txt格式檔案 來填寫字典
阿新 • • 發佈:2019-01-01
test.txt檔案
方法一:
def main(path): dict_data={} with open(path,'r') as f: txt=f.read() for t in txt.split(): key,value=t.split(':') if not key in tmp_dict: dict_data[key]=value print(dict_data) if __name__=='__main__': txtpath="D:\\test_learn_files\\test.txt" main(txtpath)
txtpath="D:\\test_learn_files\\test.txt"
dict_data = {}
with open(txtpath, 'r') as f:
for kv in [d.strip().split(':') for d in f]:
dict_data[kv[0]] = kv[1]
print(dict_data)
結果: