Basic question abou "if" from newbie
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.
floatingshed
Junior Poster in Training
66 posts since Feb 2012
Reputation Points: 23
Solved Threads: 1
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.
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
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.
floatingshed
Junior Poster in Training
66 posts since Feb 2012
Reputation Points: 23
Solved Threads: 1
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()
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294