I have a file with this format:
Description 10.01.1
;
; Find the information here
;
University
National Cantoon University
Status
National
Administrator visible
Disable
*Enable
Start Edu Fair Event
Event Only
*Event and invite user
Event and staff
Permanently Disable
*No
Yes
Order
Year 2021/Jan-Dec(14543043643)
Year 2022/Jan-Dec(56486565465)
I would like to get the value of each key.
for the example, I want to get the value of Status
which is National
If the value have more than one, then I need to get all the values, example, I need to get the value of Permanently Disable
which is *No and Yes
. I have done this in PowerShell, I use regex and trim. But now I need to use it in Python. I am new in python, anyone can help me, I really appreciated. Thank you so much
function info
{
Param($Path, $Values)
$name = $false
switch -regex -file $Path
{
$Values{ $name = $true; continue }
'^\s' { if ($name) { $_.Trim() }}
'^\S' { if ($name) { return }}
}
}
CodePudding user response:
with open('text.txt', 'r') as f:
text = f.read()
d = dict()
key = ""
# iterate line by line
for line in text.split('\n')[1:]:
# skip empty line
try:
# skip header
if line[0] == ';':
continue
# check whether first character is space
# no --> key
if not line[0].isspace():
key = line
d[key] = list()
# print("key: ", line)
# yes --> value
else:
# remove space
d[key].append(line.strip())
# print("value: ", line.strip())
except:
continue
Output:
>>> print(d) { 'University': ['National Cantoon University'], 'Status': ['National'], 'Administrator visible': ['Disable', '*Enable'], 'Start Edu Fair Event': ['Event Only', '*Event and invite user', 'Event and staff'], 'Permanently Disable': ['*No', 'Yes'], 'Order': ['Year 2021/Jan-Dec(14543043643)', 'Year 2022/Jan-Dec(56486565465)'] }