I cannot understand why this doesn't do as I expect...

if (os.path.exists(ofile)):
            os.unlink(ofile)
            print "it existed, but I've deleted it!"
        print "It didn't exist so I'm creating it"
        ---Here we have a subprocess command---

The print statements print as you'd expect but the command only runs if "ofile" doesn't already exist. i.e. the command won't run if the file has just been deleted by os.unlink.
Help appreciated.

Recommended Answers

All 3 Replies

Just to clear tings up.
Is ofile referring to a path or a file?
Just a example,and you missing a else block.

import os

ofile = r'c:\test4'
if os.path.exists(ofile):
    print 'ofile exists'
else:
    print 'ofile dont exist'

os.path.exists return True if path refers to an existing path.
Returns False for broken symbolic links.
So if "c:\test4" exist it will print "ofile exists" else "ofile dont exist"
The name ofile is confusing when os.path.exists check for path.

ofile is a path and file e.g "c:\test\test.mp3"
As I understand it the "else" statement is optional.
The print statements work exactly as you would expect.
If the file doesn't exist "It didn't exist so I'm creating it" gets printed and the subprocess runs and creates it.
If the file exists it is deleted and "it existed, but I've deleted it!" is printed. I would then expect the subprocess command to run (which creates a new file with the same name). This doesn't happen.

See if this help,it seems to work for me in this test
This script dos delete the file and create a new file in one go.

import os

ofile = r'c:\test4\t.txt'
if os.path.exists(ofile):
    print 'ofile exists'
    os.unlink(ofile)

print "It didn't exist so I'm creating it"
f = open('t.txt', 'w+')
f.close()

Here it will delete file at first run and stop.
Second run the file dont exist,so then else block will run and create the file.

import os

ofile = r'c:\test4\t.txt'
if os.path.exists(ofile):
    print 'ofile exists'
    os.unlink(ofile)
else:
    print "It didn't exist so I'm creating it"
    f = open('t.txt', 'w+')
    f.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.