[英]Python ConfigParser - Create File if it Doesn't Exist
所以我正在創建一個Python程序,它讀取一個.ini文件來為主程序設置一些啟動變量。 我唯一的想法是,我希望程序在初始化時檢查.ini文件是否存在,如果不存在,則使用一組默認值創建它。 如果有人意外刪除了該文件,那就是一種先發制人的錯誤修復方法。
我似乎無法找到任何關於如何做到這一點的例子,而且我對Python沒有超級經驗(只用它編程大約一周)所以我很感激任何幫助:)
編輯:經過進一步思考,我想進一步追求這一點。
我們假設文件確實存在。 如何檢查以確保它具有適當的部分? 如果它沒有相應的部分,我將如何刪除文件或刪除內容並重寫文件的內容?
我試圖用這個白痴證明:P
您可以使用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的新手,所以如果有人知道更好的方法讓我知道我會編輯我的答案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.