os.path.exists is not working as expected in python -
i trying create directory in home path , re-check if directory exists in home path before re-creating using os.path.exists(), not working expected.
if os.access("./", os.w_ok) not true: print("folder not writable") dir_name_tmp = subprocess.popen('pwd', stdout=subprocess.pipe, shell=true) dir_name_tmp = dir_name_tmp.stdout.read() dir_name = dir_name_tmp.split('/')[-1] dir_name = dir_name.rstrip() os.system('ls ~/') print "%s"%dir_name if not os.path.exists("~/%s"%(dir_name)): print "going create new folder %s in home path\n"%(dir_name) os.system('mkdir ~/%s'%(dir_name)) else: print "folder %s exists\n"%(dir_name) os.system('rm -rf ~/%s & mkdir ~/%s'%(dir_name, dir_name)) else : print("folder writable")
output first time:
folder not writable desktop downloads perforce bkp doc project hello.list going create new folder hello.list in home path
output 2nd time:
folder not writable desktop downloads perforce bkp doc hello.list project hello.list going create new folder hello.list in home path mkdir: cannot create directory `/home/desperado/hello.list': file exists
its not going else loop though directory existing. missing ? share in inputs !
updated working code suggestions provided: using $home directory , os.path.expandusr
if os.access("./", os.w_ok) not true: log.debug("folder not writable") dir_name_tmp = subprocess.popen('pwd', stdout=subprocess.pipe, shell=true) dir_name_tmp = dir_name_tmp.stdout.read() dir_name = dir_name_tmp.split('/')[-1] dir_name = dir_name.rstrip() log.debug("dir_name %s"%dir_name) dir_name_path = (os.path.expanduser('~/%s'%(dir_name))).rstrip() log.debug("dir_name_path %s"%(dir_name_path)) # if not os.path.exists('~/%s'%(dir_name)): if not os.path.exists('%s'%(dir_name_path)): log.debug("going create new folder %s in home path\n"%(dir_name)) os.system('mkdir $home/%s'%(dir_name)) else: log.debug("folder %s exists\n"%(dir_name)) os.system('rm -rf %s'%(dir_name_path)) os.system('mkdir $home/%s'%(dir_name)) else : log.debug("folder writable")
the tilde symbol ~
representing home directory shell convention. expanded shell in os.system
, understood literally in python.
so create <home>/<dir>
, test ~/<dir>
.
Comments
Post a Comment