Try to read file and make a dictionary from lines, skippipng lines starts with # symbol
file example:
param1=val1
# here is comment
My function:
def readFromFile(name):
config = {}
with open(name, "r") as f:
for line in f.readlines():
li=line.lstrip()
if not li.startswith("#"):
config[line.split('=')[0]] = line.split('=')[1].strip()
return config
I get list index out of range error
But! if i try to skip lines starts with, for example, symbol "h" - function works well...
Try with:
def readFromFile(name):
config = {}
with open(name, "r") as f:
for line in f.readlines():
li = line.lstrip()
if not li.startswith("#") and '=' in li:
key, value = line.split('=', 1)
config[key] = value.strip()
return config
You maybe have a blank line which breaks your split()
Your code works just fine, except for lines that neither start with a #
nor contain a =
character. Usually, those are empty lines.
Test for the =
character before splitting:
def readFromFile(name):
config = {}
with open(name, "r") as f:
for line in f.readlines():
li=line.lstrip()
if not li.startswith("#") and '=' in li:
config[line.split('=')[0]] = line.split('=')[1].strip()
return config
You can simplify the code and make it a dict comprehension:
def readFromFile(name):
with open(name, "r") as f:
return {k: v
for line in f
for (k, v) in (line.strip().split('=', 1),)
if '=' in line.strip() and line[:1] != '#'}
You can loop over f
(a file object) directly ; no need to read all lines into memory using f.readlines()
first. I used .split('=', 1)
to only split on the equals sign once .
You can return a dictionary directly:
def readFromFile(name):
with open(name) as f:
return { line.split('=')[0]:line.split('=')[1].strip() for line in f \
if not line.startswith('#' and '=' in line }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.