.. method:: read(filenames, encoding=None)
Attempt to read and parse a list of filenames, returning a list of
- filenames which were successfully parsed. If *filenames* is a string, it
- is treated as a single filename. If a file named in *filenames* cannot
- be opened, that file will be ignored. This is designed so that you can
- specify a list of potential configuration file locations (for example,
- the current directory, the user's home directory, and some system-wide
- directory), and all existing configuration files in the list will be
- read. If none of the named files exist, the :class:`ConfigParser`
+ filenames which were successfully parsed.
+
+ If *filenames* is a string or :term:`path-like object`, it is treated as
+ a single filename. If a file named in *filenames* cannot be opened, that
+ file will be ignored. This is designed so that you can specify a list of
+ potential configuration file locations (for example, the current
+ directory, the user's home directory, and some system-wide directory),
+ and all existing configuration files in the list will be read.
+
+ If none of the named files exist, the :class:`ConfigParser`
instance will contain an empty dataset. An application which requires
initial values to be loaded from a file should load the required file or
files using :meth:`read_file` before calling :meth:`read` for any
The *encoding* parameter. Previously, all files were read using the
default encoding for :func:`open`.
+ .. versionadded:: 3.6.1
+ The *filenames* parameter accepts a :term:`path-like object`.
+
.. method:: read_file(f, source=None)
import functools
import io
import itertools
+import os
import re
import sys
import warnings
Return list of successfully read files.
"""
- if isinstance(filenames, str):
+ if isinstance(filenames, (str, os.PathLike)):
filenames = [filenames]
read_ok = []
for filename in filenames:
self._read(fp, filename)
except OSError:
continue
+ if isinstance(filename, os.PathLike):
+ filename = os.fspath(filename)
read_ok.append(filename)
return read_ok
import configparser
import io
import os
+import pathlib
import textwrap
import unittest
import warnings
parsed_files = cf.read(file1)
self.assertEqual(parsed_files, [file1])
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
+ # check when we pass only a Path object:
+ cf = self.newconfig()
+ parsed_files = cf.read(pathlib.Path(file1))
+ self.assertEqual(parsed_files, [file1])
+ self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
+ # check when we passed both a filename and a Path object:
+ cf = self.newconfig()
+ parsed_files = cf.read([pathlib.Path(file1), file1])
+ self.assertEqual(parsed_files, [file1, file1])
+ self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
# check when we pass only missing files:
cf = self.newconfig()
parsed_files = cf.read(["nonexistent-file"])