Python - 轻松将文本文件内容转换为字典值/键

假设我有一个包含以下内容的文本文件:

line = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"

我想快速将这些转换为字典键/值,其中“line*”是键,引号中的文本作为值,同时删除等号。

在 Python 中执行此操作的最佳方法是什么?

最佳答案

f = open(filepath, 'r')
answer = {}
for line in f:
    k, v = line.strip().split('=')
    answer[k.strip()] = v.strip()

f.close()

希望对你有帮助

https://stackoverflow.com/questions/5942874/

相关文章:

mysql - 这是什么时间格式? (不是 UNIX,不是 UTC,什么都没有)

java - 将 4 位军用时间转换为标准 12 小时时间格式

python - 从 lxml.objectify.ObjectifiedElement 中剥离 p

c# - 使用 C# 格式化字符串中的句子

c# - 格式化难读的 try..catch..finally block ?

postgresql - 在 PostgreSQL 中格式化 double

file-io - 将数据按列写入文件(Fortran)

java - 意外的 java SimpleDateFormat 解析异常

c# - 格式化 C# 输出

arrays - Bash 数组 : appending and prepending to eac