'Using ini file with password having special characters using python configparser

new.ini file

[main]
user_name = username
password = [k!:SU`T&m5@3D\\7Z

python code

from configparser import ConfigParser
config = ConfigParser()
config.read(CONFIG.ini file path)
print(config["main"]["user_name"])
print(config["main"]["password"])

output:

username
[k!:SU`T&m5@3D\\\\7Z

After reading the file, the parsed password is not same as file input password. Help would be appreciated. Thanks



Solution 1:[1]

The password is still the same, but its representation is confusing you. The problem is the "\7" which could be interpreted as a special character. To avoid any confusion, python writes a double backslash. To see the difference, you may write the following two strings:

string_1 = "\7"
string_2 = r"\7"
print(string_1)
print(string_2)

print(repr(string_1))
print(repr(string_2))

I hope this helps you to understand the difference in what python displays.

Edit:

There should not be an extra backlash. Please try the following:

import configparser

content = r"""
[main]
user_name = username
password = [k!:SU`T&m5@3D\\7Z
"""
with open('test.ini', mode='w') as file:
    file.write(content)
parser = configparser.ConfigParser()
with open('test.ini', mode='r') as file:
    parser.read_file(file)
assert parser['main']['password'] == r"[k!:SU`T&m5@3D\\7Z"

Edit2: Please try the edited code. It should create your ini file and read in the correct password as tested with the assertion.

Edit3: I just copy pasted your ini file and ran your lines and get the correct output without extra slashes:

username
[k!:SU`T&m5@3D\\7Z

So could you please show the output of the following lines:

import platform
import sys

print(sys.version)
print(platform.platform())
print(sys.getdefaultencoding())

which in my case says:

3.8.5 (default, Sep  4 2020, 07:30:14) 
[GCC 7.3.0]
Linux-4.12.14-lp151.28.91-default-x86_64-with-glibc2.10
utf-8

Sorry, I cannot help you further, because I cannot reproduce your error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1