I have the following lines in a text file called factory.txt
Path_Folder_Name = data/1009/192/81/XYPatters/
Cloud_Site = gs://machines/inventory
M_Engine_Path = /mnt/unit/09000/UK/
I am opening it in my Python script like this:
with open('factory.txt', 'r') as factoryInfo:
Path_Folder_Name = (factoryInfo.readline().strip())
Cloud_Site = (factoryInfo.readline().strip())
M_Engine_Path = (factoryInfo.readline().strip())
How can I assign the data I am getting from the text file to a dictionary ?
I tried this, but it's not assigning the data correctly:
data = dict(
Path = Path_Folder_Name,
Cloud = Cloud_Site,
Engine = M_Engine_Path)
CodePudding user response:
Something like that ?
#!/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)
CodePudding user response:
If you want to get only the values after = sign from the text file:
Try this:
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())
