Search code examples
pythontestingfor-looppathabsolute

Python: Test if file exists at absolute path


Greetings I am a python noob who is trying to put something together. Essentially I have a ini file that contains absolute paths to files and I want python to test if the file exists. I am having an error where the file always comes up as missing and I think it has to do with the way I am formatting the path. I may be completely wrong.

Please keep in mind that the loop has not been created yet I am trying to solve this one problem first. However any advice on the rest of the program would also be appreciated. My intention is to have it loop though all sections seeing if the file labelled key exists. Then it sets a value in the config file labelled status accordingly.

here is my config file:

[server1] 
key = "C:\\test1.txt" 
status = 3

[server2] 
key = "M:\\test2.txt" 
status = 1

here is my program:

#IMPORTS
import ConfigParser
import os
import os.path
#SET SECTION NUMBER
x = 1
y = 'server'+ str(x)
#DEBUG
print y
#READ CONFIG FILE
config = ConfigParser.ConfigParser()
config.readfp(open(r'server.ini'))
key = config.get((y), 'key')
#DEBUG
print (key)
#CHECK IF FILE EXISTS
if os.path.isfile((key)):
    print "file is there"
    config.set((y), 'status', '1')
    config.write(open(r'server.ini', "w"))
else:
    print "file is missing"
    config.set((y), 'status', '3')
    config.write(open(r'server.ini', "w"))

Solution

  • If you examine the output of your program, you'll see that the key value is:

    "C:\\test1.txt"
    

    The problem is the quotes. If you get rid of those, it works okay:

    server.ini:
        [server1]
        key = C:\test1.txt
        status = 3
    
        [server2]
        key = M:\test2.txt
        status = 1
    

    If you do not have the power to change the file for some reason (it may be provided externally), you can strip off the quotes before using the key, changing:

    key = config.get((y), 'key')
    

    into:

    key = config.get((y), 'key').strip('"')
    

    You'll also notice that I've removed the double backslashes since they're something you need with string literals in your source code. Within the strings of the INI file, a single backslash works just as well.