pythonconfigparserpathlib

Python - ConfigParser and pathlib Path WindowsPath


I am reading a configuration file with ConfigParser. Until now, I was storing the paths to my files as str. I decided to improve my code by using Path from pathlib.

I now have the following error: configparser.NoSectionError: No section:. I understand from this answer that the error comes from my WindowsPath having backslashes.

Question: How can I path a WindowsPath to ConfigParser without throwing an error?


Solution

  • You're getting configparser.NoSectionError not because you're using WindowsPath or backslashes — it's because you're calling set() or get() on a section that doesn't exist yet.

    Solution:

    Before setting a path, make sure to add the section:

    from configparser import ConfigParser
    from pathlib import Path
    
    config = ConfigParser()
    config.add_section('Paths')  # Add this line
    
    config.set('Paths', 'file', str(Path(r'C:\Users\Example\File.txt')))
    
    with open('config.ini', 'w') as f:
        config.write(f)
    

    Reading it back:

    config.read('config.ini')
    file_path = Path(config.get('Paths', 'file'))