python写入ini文件,没有该文件自动创建
时间: 2023-12-18 08:04:30 浏览: 26
在使用 ConfigParser 模块写入 INI 文件时,如果指定的文件不存在,则会自动创建该文件。以下是一个示例代码:
```python
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 添加一些配置
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
# 写入到文件
with open('example.ini', 'w') as configfile:
config.write(configfile)
```
以上代码将创建一个名为 example.ini 的文件,并添加一些配置。如果该文件不存在,则会自动创建。
相关问题
python 创建一个ini文件
可以使用 Python 中的 ConfigParser 模块来创建和读取 INI 文件。以下是一个示例代码:
```python
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 添加一些配置
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
# 写入到文件
with open('example.ini', 'w') as configfile:
config.write(configfile)
```
以上代码将创建一个名为 example.ini 的文件,并添加一些配置。你可以根据需要自定义配置。最后,使用 write() 方法将配置写入文件。
python 读写ini文件
要读写INI文件,可以使用Python标准库中的configparser模块。以下是一个简单的示例:
```python
import configparser
# 读取INI文件
config = configparser.ConfigParser()
config.read('config.ini')
# 获取指定section和option的值
value = config.get('section_name', 'option_name')
# 修改指定section和option的值
config.set('section_name', 'option_name', 'new_value')
# 写入INI文件
with open('config.ini', 'w') as f:
config.write(f)
```
在上面的代码中,我们首先创建一个ConfigParser对象,并使用read方法读取INI文件。然后,我们可以使用get方法获取指定section和option的值,使用set方法修改指定section和option的值。最后,我们使用write方法将更改写入INI文件。