gpt4 book ai didi

Python - 从文件中读取跳过行以 # 开头

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:08 33 4
gpt4 key购买 nike

尝试读取文件并根据行创建字典,跳过以#符号开头的行

文件示例:

param1=val1
# here is comment

我的功能:

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

我收到列表索引超出范围的错误

但是!如果我尝试跳过以符号“h”开头的行 - 功能运行良好......

最佳答案

尝试:

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

你可能有一个空行打破了你的 split()

关于Python - 从文件中读取跳过行以 # 开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17969776/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com