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

Python - converting textfile contents into dictionary values/keys easily(Python - 轻松将文本文件内容转换为字典值/键)
本文介绍了Python - 轻松将文本文件内容转换为字典值/键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

Let's say I have a text file with the following:

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

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

And I want to quickly convert these into dictionary keys/values with " line* " being the key and the text in quotes as the value while also removing the equals sign.

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

What would be the best way to do this in Python?

推荐答案

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

f.close()

希望对你有帮助

这篇关于Python - 轻松将文本文件内容转换为字典值/键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why does Python#39;s IDLE crash when I type a parenthesis on Mac?(为什么我在 Mac 上键入括号时 Python 的 IDLE 会崩溃?)
Tkinter crashes Jupyter kernel?(Tkinter 崩溃 Jupyter 内核?)
IDLE crash when opening on Mac OS X(在 Mac OS X 上打开时 IDLE 崩溃)
GVIM crashes when running python(运行 python 时 GVIM 崩溃)
PySide: Segfault(?) when using QItemSelectionModel with QListView(PySide:将 QItemSelectionModel 与 QListView 一起使用时的 Segfault(?))
Why does PyQt sometimes crash on exit?(为什么 PyQt 有时会在退出时崩溃?)