I am writing a fairly simple journal entry program, and I need to check if a directory exists and if it doesn’t, I need to create one.
In journal.py I am importing another module: files. This module handles the creation and deletion of files and directories
journal.py
if __name__ == '__main__':
if files.testForDir('entries') == False:
print 'Directory "entries" does not exist'
print 'Attempting to create directory'
files.createDir('entires')
files.py
def testForDir(dirname, path=os.getcwd()):
pathtotest = os.path.join(path, dirname)
return os.path.isdir(pathtotest)
def createDir(dirname, path=os.getcwd()):
dirpath = os.path.join(path, dirname)
try:
os.mkdir(dirpath)
except OSError as error:
print error
My problem: When I create the directory inside Ubuntu, testForDir() returns the correct result. It also runs correctly when I run the program without /entries. It creates the directory using os.mkdir() and /entries shows up in Ubuntu. However, when I run it after the directory was created by os.mkdir(), testForDir() returns False and an OSError exception is raised as the folder already exists.
So to present the problem formally, and repeat myself: When I create a directory using os.mkdir(), os.path.isdir() tells me the directory does not exist.
System Information: Ubuntu 12.04 LTS 32bit, Python 2.7.
File structure: home/name/Programs/journal/.
Journal contains: entries.py(blank), files.py, journal.py, entries(dir)
You have a spelling mistake:
stop hardcoding the same string in multiple places (mis-spelling is one risk, but it’s also unnecessarily painful to change later).
Put it in a variable, and Python will be able to warn you if you mis-spell the variable name.