簡體   English   中英

使用python從.txt文件中的鍵值對中提取值

[英]Extracting value from a key value pair in a .txt file using python

我有一個文本文件,其中包含一行包含鍵和值的一行。 例如:姓名:xyz

從python如何導入文本文件並獲取名稱,即xyz

open('filename.txt').readline().split(':')[1].strip()
  • open('filename.txt')打開文件
  • .read讀取行
  • .split(':')[1]:上分割行,並獲取第二個元素(值)
  • .strip()從第一個空格中.strip()

根據使用情況,如果您需要存儲更多值,我認為最干凈的解決方案是使用python中的config模塊。 在那里,您無需自己解析任何內容:

https://docs.python.org/2/library/configparser.html

除此之外,您可以像已經在注釋中建議的那樣讀出文件

可能看起來像這樣:

from ConfigParser import SafeConfigParser

cf_parser = SafeConfigParser()
cf_parser.read("file")
name = cf_parser.get("section", "name")

該文件可能如下所示:

[section]
name = xyz

如果文件名為keyfile.txt,則可以執行以下操作:

f = open('keyfile.txt')
s = f.readline()
s.split()[1]

試一下。 它使用列表推導功能,並使用Python 2.7在本地計算機上處​​理了像您這樣的文件

with open("your_file.txt", "r") as file:
    rows = ( line.split(':') for line in file)
    dict = { row[0]:row[1] for row in rows }
for item in dict:
    print dict[item]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM