我想从属性文件中读取,并根据fi的键将该值放入字符串中

2024-09-30 12:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新学习python的,我必须处理文件中的属性文件,值将出现在键值对中,以及我认为如何读取文件,但不能存储或打印基于键的值。

我试过用pip安装的jproperties库,我已经读取了对象中的值,但无法从中获取记录。 已经浏览了https://pypi.org/project/jproperties/#parsing-a-property-file网站以供参考

from jproperties import Properties

class PropertiesReader:
    p = Properties()
    with open("foobar.properties", "rt") as f:
        p.load(f, "utf-8")

    s = p.__getitem__("name","value")
    z = p.__getattribute__("email","mail")
    print(s)
    print(z)

以及属性文件

^{pr2}$

输出是

Traceback (most recent call last):
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 4, in <module>
    class PropertiesReader:
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 7, in PropertiesReader
    p.load(f, "utf-8")
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 804, in load
    self._parse()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 731, in _parse
    while self._parse_logical_line():
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 686, in _parse_logical_line
    self._skip_whitespace()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 438, in _skip_whitespace
    c = self._peek()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 378, in _peek
    c = self._source_file.read(1)
  File "/usr/local/lib/python3.7/codecs.py", line 500, in read
    data = self.bytebuffer + newdata
TypeError: can't concat str to bytes

Process finished with exit code 1

我想打印

Harsh
abc.xyz

Tags: 文件inpyselfparselibpackagesusr
2条回答

测试以下代码:https://repl.it/repls/EmptyRowdyCategories

from jproperties import Properties

p = Properties()
with open("foobar.properties", "rb") as f:
    p.load(f, "utf-8")


print(p["name"].data)
print(p["email"].data)

打开文件的方式就像打开文本文件一样:

with open("foobar.properties", "rt") as f:
    p.load(f, "utf-8")

但是jproperties docs显示您需要以二进制模式打开文件:

^{pr2}$

相关问题 更多 >

    热门问题