I am trying to read a configuration file in python 3.7 using SafeConfigParser. I have tried giving the full file name (with file location), giving only file name (without file location), using readfp function in SafeConfigParser, using only configparser instead of safeconfigparser but none of them have worked. I am 100% sure that at least the correct file is being read.
Here is my python code:
from configparser import SafeConfigParser
import os
def main():
filename = "C:/Users/Umer Sherdil Paracha/Desktop/distutils.cfg"
if os.path.isfile(filename):
parser = SafeConfigParser()
parser.read(filename)
print(parser.sections())
screen_width = parser.getint('graphics','width')
screen_height = parser.getint('graphics','height')
else:
print("Config file not found")
if __name__=="__main__":
main()
and here is my cfg file:
[GRAPHICS]
height = 600
width = 800
I am totally stuck on this stupid problem. Any help in this regard would be appreciated. Thank you.
It's tough to say for sure, but my guess is there's something wrong with your filename string.
Try this piece of debug code first:
My guess it that will throw you a file not found error. There are likely a couple reasons for this (though you can always double-check that you have the right path by right-clicking on the file and opening properties):
r"\I will not \escape the backslashes"I believe your filename variable should look like this:
If you make both of these changes in your file string, I suspect the above test code will work and so will your real code after making these changes.
Once you're successfully able to open your file, remember that python is always case sensitive, so you'll have to update the following two lines of code as below to reflect the case used in your .cfg file: