configparser Not Recognizing Sections in config.ini

94 Views Asked by At

I'm trying to use the configparser module in Python to read from a config.ini file. Despite having a [example_section] in my config.ini file, when I run my script, it keeps printing that the section isn't found.

Python Script:

import boto3
import configparser

s3 = boto3.client('s3')

ROLE = 'example_section'

config = configparser.ConfigParser()
config.read('../config.ini')

if ROLE in config:
    BUCKET_NAME = config[ROLE]['BUCKET_NAME']
else:
    print(f"'{ROLE}' section not found in the config file.")

BUCKET_NAME = config[ROLE]['BUCKET_NAME']
FILE_NAME = config[ROLE]['FILE_NAME']
BUCKET_OUTPUT = config[ROLE]['BUCKET_OUTPUT']
OUTPUT_FILE_NAME = config[ROLE]['OUTPUT_FILE_NAME']

Config File (config.ini):

[example_section]
BUCKET_NAME = s3-example-data-input
FILE_NAME = example_section/example_file_name.csv
BUCKET_OUTPUT = s3-example-data-output
OUTPUT_FILE_NAME = example_section/example_output_file_name.csv

[another_section]
BUCKET_NAME = s3-example-data-input
FILE_NAME = another_section/another_file_name.csv
BUCKET_OUTPUT = s3-example-data-output
OUTPUT_FILE_NAME = another_section/another_output_file_name.csv

[yet_another_section]
BUCKET_NAME = s3-example-data-input
FILE_NAME = yet_another_section/file_name.csv
BUCKET_OUTPUT = s3-example-data-output
OUTPUT_FILE_NAME = yet_another_section/output_file_name.csv

[final_section]
BUCKET_NAME = s3-example-data-input
FILE_NAME = final_section/file_name.csv
BUCKET_OUTPUT = s3-example-data-output
OUTPUT_FILE_NAME = final_section/output_file_name.csv

What I tried:

I'm attempting to use the configparser module to extract values from a config.ini file. I've set up the config.ini file with several sections, and in my script, I'm trying to access the [example_section] to retrieve values associated with keys inside it.

What I expected:

Given the presence of the [example_section] in my config.ini file, I expected my script to recognize this section and successfully extract the values of BUCKET_NAME, FILE_NAME, BUCKET_OUTPUT, and OUTPUT_FILE_NAME.

What actually happened:

When I run the script, it prints that the [example_section] isn't found in the config.ini file, even though I've confirmed that it's present. I also ensured the path to the config.ini file is correct, and when I read and print the content of the file, it appears as expected. The puzzling aspect is why configparser isn't recognizing the sections, even though they are clearly present in the file.

0

There are 0 best solutions below