我在名為的文本檔案中有以下幾行 factory.txt
Path_Folder_Name = data/1009/192/81/XYPatters/
Cloud_Site = gs://machines/inventory
M_Engine_Path = /mnt/unit/09000/UK/
我在我的 Python 腳本中打開它,如下所示:
with open('factory.txt', 'r') as factoryInfo:
Path_Folder_Name = (factoryInfo.readline().strip())
Cloud_Site = (factoryInfo.readline().strip())
M_Engine_Path = (factoryInfo.readline().strip())
如何將從文本檔案中獲取的資料分配給字典?
我試過這個,但它沒有正確分配資料:
data = dict(
Path = Path_Folder_Name,
Cloud = Cloud_Site,
Engine = M_Engine_Path)
uj5u.com熱心網友回復:
類似的東西?
#!/usr/bin/env python3
# coding: utf-8
data = {}
with open("factory.txt", "r") as file:
for line in file:
tokens = line.split("=")
if len(tokens) != 2:
raise Exception("Invalid config file")
key = tokens[0].strip()
value = tokens[1].strip()
if key in data:
raise Exception(f"key '{key}' is defined twice")
data[key] = value
print(data)
uj5u.com熱心網友回復:
如果您只想=從文本檔案中獲取sign后的值:
嘗試這個:
with open('factory.txt', 'r') as factoryInfo:
Path_Folder_Name = factoryInfo.readline().strip()
Cloud_Site = factoryInfo.readline().strip()
M_Engine_Path = factoryInfo.readline().strip()
data = dict(
Path = Path_Folder_Name.split("=")[1].strip(),
Cloud = Cloud_Site.split("=")[1].strip(),
Engine = M_Engine_Path.split("=")[1].strip())
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341413.html
下一篇:C#:回傳陳述句末尾的生成器
