0
# File Operations
1
2
Methods for reading configuration data from various sources (files, strings, dictionaries) and writing configuration data back to files. These operations form the core I/O capabilities of the configparser library.
3
4
## Capabilities
5
6
### Reading from Files
7
8
Load configuration data from one or more files, with support for encoding specification and error handling.
9
10
```python { .api }
11
def read(filenames, encoding=None):
12
"""
13
Read and parse configuration files.
14
15
Parameters:
16
- filenames: str or iterable of str, file paths to read
17
- encoding: str, text encoding (defaults to locale default)
18
19
Returns:
20
list of str: successfully read file names
21
22
Notes:
23
- Non-existent files are silently ignored
24
- Later files override earlier ones for duplicate options
25
"""
26
27
def read_file(f, source=None):
28
"""
29
Read configuration from a file-like object.
30
31
Parameters:
32
- f: file-like object, must have readline() method
33
- source: str, name for error messages (defaults to f.name)
34
35
Returns:
36
None
37
38
Raises:
39
- ParsingError: if file cannot be parsed
40
"""
41
```
42
43
### Reading from Strings and Dictionaries
44
45
Load configuration data from string literals or dictionary objects, useful for programmatic configuration.
46
47
```python { .api }
48
def read_string(string, source='<string>'):
49
"""
50
Read configuration from a string.
51
52
Parameters:
53
- string: str, configuration data in INI format
54
- source: str, name for error messages
55
56
Returns:
57
None
58
59
Raises:
60
- ParsingError: if string cannot be parsed
61
"""
62
63
def read_dict(dictionary, source='<dict>'):
64
"""
65
Read configuration from a dictionary.
66
67
Parameters:
68
- dictionary: dict, nested dictionary {section: {option: value}}
69
- source: str, name for error messages
70
71
Returns:
72
None
73
74
Notes:
75
- Dictionary keys become section names
76
- Nested dictionary values become options
77
- All keys and values are converted to strings
78
"""
79
```
80
81
### Writing Configuration
82
83
Save configuration data to files in standard INI format.
84
85
```python { .api }
86
def write(fp, space_around_delimiters=True):
87
"""
88
Write configuration to a file-like object.
89
90
Parameters:
91
- fp: file-like object, must have write() method
92
- space_around_delimiters: bool, add spaces around '=' in output
93
94
Returns:
95
None
96
97
Notes:
98
- Writes in standard INI format
99
- DEFAULT section is written first if present
100
- Comments and original formatting are not preserved
101
"""
102
```
103
104
## Usage Examples
105
106
### Reading from Multiple Files
107
108
```python
109
from backports import configparser
110
111
config = configparser.ConfigParser()
112
113
# Read from multiple files (later files override earlier ones)
114
files_read = config.read(['default.ini', 'user.ini', 'local.ini'])
115
print(f"Successfully read: {files_read}")
116
117
# Read with explicit encoding
118
config.read('config.ini', encoding='utf-8')
119
```
120
121
### Reading from File Objects
122
123
```python
124
from backports import configparser
125
import io
126
127
config = configparser.ConfigParser()
128
129
# Read from file object
130
with open('config.ini', 'r', encoding='utf-8') as f:
131
config.read_file(f)
132
133
# Read from StringIO
134
config_data = """
135
[section1]
136
option1 = value1
137
option2 = value2
138
"""
139
config.read_file(io.StringIO(config_data), source='memory')
140
```
141
142
### Reading from Strings
143
144
```python
145
from backports import configparser
146
147
config = configparser.ConfigParser()
148
149
# Read configuration from string
150
config_string = '''
151
[database]
152
host = localhost
153
port = 5432
154
name = myapp
155
156
[cache]
157
enabled = true
158
timeout = 300
159
'''
160
161
config.read_string(config_string)
162
```
163
164
### Reading from Dictionaries
165
166
```python
167
from backports import configparser
168
169
config = configparser.ConfigParser()
170
171
# Read from dictionary
172
config_dict = {
173
'database': {
174
'host': 'localhost',
175
'port': '5432',
176
'name': 'myapp'
177
},
178
'cache': {
179
'enabled': 'true',
180
'timeout': '300'
181
}
182
}
183
184
config.read_dict(config_dict)
185
```
186
187
### Writing Configuration
188
189
```python
190
from backports import configparser
191
192
config = configparser.ConfigParser()
193
config.add_section('database')
194
config.set('database', 'host', 'localhost')
195
config.set('database', 'port', '5432')
196
197
# Write to file
198
with open('output.ini', 'w') as f:
199
config.write(f)
200
201
# Write to string
202
import io
203
output = io.StringIO()
204
config.write(output, space_around_delimiters=False)
205
config_string = output.getvalue()
206
```
207
208
### Error Handling
209
210
```python
211
from backports import configparser
212
213
config = configparser.ConfigParser()
214
215
try:
216
config.read('nonexistent.ini') # Silently ignores missing files
217
config.read_string('invalid [section without closing bracket')
218
except configparser.ParsingError as e:
219
print(f"Parsing error: {e}")
220
for filename, lineno, line in e.errors:
221
print(f"File: {filename}, Line {lineno}: {line}")
222
```