पायथन: आप एक साधारण सेटिंग / कॉन्फिग फाइल को कैसे सेव करेंगे?


101

मुझे परवाह नहीं है यह है कि अगर JSON, pickle, YAML, या जो कुछ भी।

अन्य सभी कार्यान्वयन जिन्हें मैंने देखा है, वे संगत नहीं हैं, इसलिए यदि मेरे पास एक कॉन्फ़िग फ़ाइल है, तो कोड में एक नई कुंजी जोड़ें, फिर उस कॉन्फ़िग फ़ाइल को लोड करें, यह बस दुर्घटनाग्रस्त हो जाएगा।

क्या ऐसा करने का कोई सरल तरीका है?


1
मेरा मानना .iniहै कि configparserमॉड्यूल के समान प्रारूप का उपयोग करना चाहिए जो आपको चाहिए।
बकुरीउ सिप

14
सही के रूप में मेरे जवाब का चयन करने का कोई भी मौका?
ग्रीम स्टुअर्ट

जवाबों:


187

अजगर में विन्यास फाइल

आवश्यक फ़ाइल प्रारूप के आधार पर ऐसा करने के कई तरीके हैं।

विन्यासकर्ता [.ini प्रारूप]

जब तक एक अलग प्रारूप का उपयोग करने के लिए सम्मोहक कारण नहीं थे , मैं मानक विन्यासक दृष्टिकोण का उपयोग करूंगा

एक फ़ाइल को इस तरह लिखें:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')

with open('config.ini', 'w') as f:
    config.write(f)

वर्गाकार कोष्ठक में चिह्नित वर्गों के साथ फ़ाइल प्रारूप बहुत सरल है:

[main]
key1 = value1
key2 = value2
key3 = value3

मान फ़ाइल से निकाले जा सकते हैं जैसे:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')

print config.get('main', 'key1') # -> "value1"
print config.get('main', 'key2') # -> "value2"
print config.get('main', 'key3') # -> "value3"

# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')

# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')

JSON [.json प्रारूप]

JSON डेटा बहुत जटिल हो सकता है और अत्यधिक पोर्टेबल होने का फायदा है।

फ़ाइल में डेटा लिखें:

import json

config = {'key1': 'value1', 'key2': 'value2'}

with open('config.json', 'w') as f:
    json.dump(config, f)

एक फ़ाइल से डेटा पढ़ें:

import json

with open('config.json', 'r') as f:
    config = json.load(f)

#edit the data
config['key3'] = 'value3'

#write it back to the file
with open('config.json', 'w') as f:
    json.dump(config, f)

YAML

इस जवाब में एक बुनियादी YAML उदाहरण दिया गया है । अधिक विवरण pyYAML वेबसाइट पर देखे जा सकते हैं ।


8
अजगर 3 में from configparser import ConfigParser config = ConfigParser()
user3148949

12

ConfigParser मूल उदाहरण

फ़ाइल को इस तरह लोड और इस्तेमाल किया जा सकता है:

#!/usr/bin/env python

import ConfigParser
import io

# Load the configuration file
with open("config.yml") as f:
    sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))

# List all contents
print("List all contents")
for section in config.sections():
    print("Section: %s" % section)
    for options in config.options(section):
        print("x %s:::%s:::%s" % (options,
                                  config.get(section, options),
                                  str(type(options))))

# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous'))  # Just get the value
print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?

जो आउटपुट देता है

List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>

Print some contents
yes
True

जैसा कि आप देख सकते हैं, आप एक मानक डेटा प्रारूप का उपयोग कर सकते हैं जो पढ़ने और लिखने में आसान है। गेटबुलियन और गेटिंट जैसे तरीके आपको एक साधारण स्ट्रिंग के बजाय डेटाटाइप प्राप्त करने की अनुमति देते हैं।

लेखन विन्यास

import os
configfile_name = "config.yaml"

# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
    # Create the configuration file as it doesn't exist yet
    cfgfile = open(configfile_name, 'w')

    # Add content to the file
    Config = ConfigParser.ConfigParser()
    Config.add_section('mysql')
    Config.set('mysql', 'host', 'localhost')
    Config.set('mysql', 'user', 'root')
    Config.set('mysql', 'passwd', 'my secret password')
    Config.set('mysql', 'db', 'write-math')
    Config.add_section('other')
    Config.set('other',
               'preprocessing_queue',
               ['preprocessing.scale_and_center',
                'preprocessing.dot_reduction',
                'preprocessing.connect_lines'])
    Config.set('other', 'use_anonymous', True)
    Config.write(cfgfile)
    cfgfile.close()

का परिणाम

[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math

[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True

XML मूल उदाहरण

लगता है कि पायथन समुदाय द्वारा कॉन्फ़िगरेशन फ़ाइलों के लिए बिल्कुल भी उपयोग नहीं किया जाएगा। हालाँकि, XML को पार्स करना / लिखना आसान है और पायथन के साथ ऐसा करने की काफी संभावनाएं हैं। एक सुंदर है:

from BeautifulSoup import BeautifulSoup

with open("config.xml") as f:
    content = f.read()

y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
    print(tag)

जहाँ config.xml इस तरह दिख सकता है

<config>
    <mysql>
        <host>localhost</host>
        <user>root</user>
        <passwd>my secret password</passwd>
        <db>write-math</db>
    </mysql>
    <other>
        <preprocessing_queue>
            <li>preprocessing.scale_and_center</li>
            <li>preprocessing.dot_reduction</li>
            <li>preprocessing.connect_lines</li>
        </preprocessing_queue>
        <use_anonymous value="true" />
    </other>
</config>

अच्छा कोड / उदाहरण। मामूली टिप्पणी - आपका YAML उदाहरण YAML लेकिन INI शैली प्रारूप का उपयोग नहीं कर रहा है।
एरिक क्रेमर

यह ध्यान दिया जाना चाहिए कि कम से कम configParser के अजगर 2 संस्करण चुपचाप संग्रहीत सूची को पढ़ने पर स्ट्रिंग में बदल देंगे। अर्थात। CP.set ('खंड', 'विकल्प', [1,2,3]) को सहेजने और पढ़ने के बाद विन्यास CP.get ('खंड', 'विकल्प') => '1, 2, 3' होगा
Gnudiff

10

यदि आप सेटिंग्स को होल्ड करने के लिए INI फ़ाइल जैसी किसी चीज़ का उपयोग करना चाहते हैं, तो configparser का उपयोग करने पर विचार करें जो टेक्स्ट फ़ाइल से मुख्य मूल्य जोड़े लोड करता है, और आसानी से फ़ाइल में वापस लिख सकता है।

INI फ़ाइल का प्रारूप है:

[Section]
key = value
key with spaces = somevalue

2

शब्दकोश को सहेजें और लोड करें। आपके पास कुंजी, मान जोड़े की मनमानी कुंजी, मान और मनमानी संख्या होगी।


क्या मैं इसके साथ रिफैक्टरिंग का उपयोग कर सकता हूं?
लोर


-2

cfg4py का उपयोग करके देखें :

  1. Hierarchichal डिजाइन, mulitiple env ने समर्थन किया, इसलिए उत्पादन साइट सेटिंग्स के साथ देव सेटिंग्स को कभी भी गड़बड़ न करें।
  2. कोड पूरा हो रहा है। Cfg4py आपके याम्ल को एक अजगर वर्ग में बदल देगा, तब कोड पूरा होने पर आप अपना कोड टाइप करते हुए उपलब्ध होंगे।
  3. बहुत अधिक..

अस्वीकरण: मैं इस मॉड्यूल का लेखक हूं

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.