あなたがConfigParserとOSライブラリを使用することができ、ここでは簡単な例です:
#!usr/bin/python
import configparser, os
config = configparser.ConfigParser()
# Just a small function to write the file
def write_file():
config.write(open('config.ini', 'w'))
if not os.path.exists('config.ini'):
config['testing'] = {'test': '45', 'test2': 'yes'}
write_file()
else:
# Read File
config.read('config.ini')
# Get the list of sections
print config.sections()
# Print value at test2
print config.get('testing', 'test2')
# Check if file has section
try:
config.get('testing', 'test3')
# If it doesn't i.e. An exception was raised
except configparser.NoOptionError:
print "NO OPTION CALLED TEST 3"
# Delete this section, you can also use config.remove_option
# config.remove_section('testing')
config.remove_option('testing', 'test2')
write_file()
出力:
[DEFAULT]
test = 45
test2 = yes
上記のは、詳細を知るのに非常に便利なドキュメントです構成ファイルやその他の組み込みモジュールの作成について
ノート:私はPythonの初心者です。誰かがより良いアプローチを知っていれば、私は私の答えを編集します!
ありがとうございました:)前にではなく、 'if not os.path.exists(pathName)'の後にキーを定義するコードを置く方が意味がありますか?そうすれば、ファイルが存在しなければプログラムを実行する必要はありませんか? – Skitzafreak
@Skitzafreakまた、パーサーがifステートメント内で定義されているところに、3行目と4行目の両方を入れることもできます。私があなたの質問に答えた場合は、チックボタンで間違いなくそれをマークして、他の人がこの質問に答えていることを知ってください。 – hallaksec
申し訳ございません。助けてくれてありがとう: – Skitzafreak