[英]How to read multiline .properties file in python
我正在嘗試讀取java多行i18n屬性文件。 有這樣的行:
messages.welcome=Hello\
World!
messages.bye=bye
使用此代碼:
import configobj
properties = configobj.ConfigObj(propertyFileName)
但是對於多行值,它會失敗。
有什么建議?
根據ConfigObj文檔 , configobj
要求您用三引號括起多行值:
包含換行符(多行值)的值可以用三引號括起來。 如果值包含兩種類型的引號,也可以使用這些。 列表成員不能被三重引號包圍:
如果修改屬性文件是不可能的 ,我建議使用configparser :
在配置解析器中,值可以跨越多行,只要它們比包含它們的鍵縮進更多。 默認情況下,解析器還允許空行成為值的一部分。
這是一個概念的快速證明:
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
try:
import ConfigParser as configparser
except ImportError:
import configparser
try:
import StringIO
except ImportError:
import io.StringIO as StringIO
test_ini = """
[some_section]
messages.welcome=Hello\
World
messages.bye=bye
"""
config = configparser.ConfigParser()
config.readfp(StringIO.StringIO(test_ini))
print(config.items('some_section'))
輸出:
[('messages.welcome','Hello World'),('messages.bye','bye')]
謝謝你的回答,這就是我最終做的:
這是代碼的摘錄:
#!/usr/bin/python
...
# Add the section
subprocess.Popen(['/bin/bash','-c','sed -i \'1i [default]\' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)
# Remove empty lines
subprocess.Popen(['/bin/bash','-c','sed -i \'s/^$/#/g' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)
# Get all i18n files
files=glob.glob(srcDirectory+"/"+baseFileName+"_*.properties")
config = ConfigParser.ConfigParser()
for propFile in files:
...
config.read(propertyFileName)
value=config.get('default',"someproperty")
...
# Remove section
subprocess.Popen(['/bin/bash','-c','sed -i \'1d\' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)
對於那些不以空白空間開頭的多線,我仍然遇到麻煩。 我只是手動修復它們,但是sed可以做到這一點。
格式化屬性文件,如下所示:
messages.welcome="""Hello
World!"""
messages.bye=bye
嘗試一下ConfigParser
我不清楚Java湯中的任何內容,但正如我所希望的那樣,正則表達式可以幫到你:
import re
ch = '''messages.welcome=Hello
World!
messages.bye=bye'''
regx = re.compile('^(messages\.[^= \t]+)[ \t]*=[ \t]*(.+?)(?=^messages\.|\Z)',re.MULTILINE|re.DOTALL)
print regx.findall(ch)
結果
[('messages.welcome', 'Hello\n World! \n'), ('messages.bye', 'bye')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.