1

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.

user3673471
  • 11
  • 2
  • 3

2 Answers2

0

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:

filename = "C:/Users/Umer Sherdil Paracha/Desktop/distutils.cfg"
with open(filename) as file:
    print("Successfully got to this line!")

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):

  1. You're using unix style slashes. Windows typically uses backslashes ()
  2. When you start using backslashes in strings, python can get confused as backslashes are also used to escape special characters. Tell python that this is a raw string by adding an r before the starting quote: r"\I will not \escape the backslashes"

I believe your filename variable should look like this:

filename = r"C:\Users\Umer Sherdil Paracha\Desktop\distutils.cfg"

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:

screen_width = parser.getint('GRAPHICS','width')
screen_height = parser.getint('GRAPHICS','height')
Daniel Long
  • 1,162
  • 14
  • 30
-1

With Windows ini files use

r'pathname'  

to identify files.

r"pathname"

may also work. In my case, without the "r" Python did not error on ConfigParser.read, it just failed to find the section.

John P. Fisher
  • 267
  • 1
  • 6