How can I check how much of a path exists in python - python

Let's say on my filesystem the following directory exists:
/foo/bar/
In my python code I have the following path:
/foo/bar/baz/quix/
How can I tell that only the /foo/bar/ part of the path exists?
I can walk the path recursively and check it step by step, but is there an easier way?

No easy function in the standard lib but not really a difficult one to make yourself.
Here's a function that takes a path and returns only the path that does exist.
In [129]: def exists(path):
...: if os.path.exists(path): return path
...: return exists(os.path.split(path)[0])
...:
In [130]: exists("/home/sevanteri/src/mutta/oisko/siellä/jotain/mitä/ei ole/")
Out[130]: '/home/sevanteri/src'

I think a simple while loop with os.path.dirname() will suffice the requirement
path_string = '/home/moin/Desktop/my/dummy/path'
while path_string:
if not os.path.exists(path_string):
path_string = os.path.dirname(path_string)
else:
break
# path_string = '/home/moin/Desktop' # which is valid path in my system

I don't actually get your requirements as whether you want every path to be checked or upto some specific level.But for simple sanity checks you can just iterate through the full path create the paths and check the sanity.
for i in filter(lambda s: s, sample_path.split('/')):
_path = os.path.join(_path, i)
if os.path.exists(_path):
print "correct path"

Well, I think the only way is to work recursively... Though, I would work up the directory tree. The code isn't too hard to implement:
import os
def doesItExist(directory):
if not os.path.exists(directory):
doesItExist(os.path.dirname(directory)
else:
print "Found: " + directory
return directory

Related

check for a folder with python

if os.chdir(path+"micro")==True:
os.chdir(path+"micro")
else:
os.mkdir(path+"micro")
os.chdir(path+"micro")
when I use this method it gives me an error and says file exitsts why can't I access that file
If I understand your question correctly, this code is for you:
if os.path.exists(path+"micro"):
os.chdir(path+"micro")
else:
os.mkdir(path+"micro")
os.chdir(path+"micro")
Your code was incorrect because as you can see from the documentation os.chdir does not return any value, but is used to change the current working directory to the given path. Returns None in all the cases. For this reason your code gave an error.
Instead you need the os.path.exists method which return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.
I think what you are trying to do is:
dir = os.path.join(path, "micro")
if not os.path.isdir(dir):
os.mkdir(dir)
os.chdir(dir)
os.chdir(path+"micro") This does not return false if the path doesn't exist. It rather gives an error. Also writing path + "mirco" is not a good practice either. The standard way is using os.path.join(path, "micro") because it handles choosing "/" or "\" according to the os it is running on.
So these are some alternatives that you might try.
Alternative 1:
dir = os.path.join(path, "micro")
if not os.path.exists(dir):
os.mkdir(dir)
os.chdir(dir)
Alternative 2:
dir = os.path.join(path, "micro")
try:
os.chdir(dir)
except:
os.mkdir(dir)
os.chdir(dir)

Python os.linkdir

import os
path = "D:\uda\prank\photo"
def rename_files():
print os.path.exists(path)
if os.path.exists(path):
print("exists")
file_list = os.listdir(path)
print(file_list)
else:
print("No luck")
I'm trying to print a list of filenames using os.listdir method, however nothing appeared even from "exists" or "No luck", so what could be happening over here? I thought it was because of administrator's restriction, however now I'm pretty sure that won't bother at all. Please help!
You have defined a function (rename_files), but never call it (at least from the posted code).

Check if a given directory contains any directory in python

Essentially, I'm wondering if the top answer given to this question can be implemented in Python. I am reviewing the modules os, os.path, and shutil and I haven't yet been able to find an easy equivalent, though I assume I'm just missing something simple.
More specifically, say I have a directory A, and inside directory A is any other directory. I can call os.walk('path/to/A') and check if dirnames is empty, but I don't want to make the program go through the entire tree rooted at A; i.e. what I'm looking for should stop and return true as soon as it finds a subdirectory.
For clarity, on a directory containing files but no directories an acceptable solution will return False.
maybe you want
def folders_in(path_to_parent):
for fname in os.listdir(path_to_parent):
if os.path.isdir(os.path.join(path_to_parent,fname)):
yield os.path.join(path_to_parent,fname)
print(list(folders_in("/path/to/parent")))
this will return a list of all subdirectories ... if its empty then there are no subdirectories
or in one line
set([os.path.dirname(p) for p in glob.glob("/path/to/parent/*/*")])
although for a subdirectory to be counted with this method it must have some file in it
or manipulating walk
def subfolders(path_to_parent):
try:
return next(os.walk(path_to_parent))[1]
except StopIteration:
return []
I would just do as follows:
#for example
dir_of_interest = "/tmp/a/b/c"
print(dir_of_interest in (v[0] for v in os.walk("/tmp/")))
This prints True or False, depending if dir_of_interest is in the generator. And you use here generator, so the directories to check are generated one by one.
You can break from the walk anytime you want. For example, this brakes is a current folder being walked, has no subdirectories:
for root, dirs, files in os.walk("/tmp/"):
print(root,len(dirs))
if not len(dirs): break
Maybe this is in line with what you are after.
Try this:
#!/usr/local/cpython-3.4/bin/python
import glob
import os
top_of_hierarchy = '/tmp/'
#top_of_hierarchy = '/tmp/orbit-dstromberg'
pattern = os.path.join(top_of_hierarchy, '*')
for candidate in glob.glob(pattern):
if os.path.isdir(candidate):
print("{0} is a directory".format(candidate))
break
else:
print('No directories found')
# Tested on 2.6, 2.7 and 3.4
I apparently can't comment yet; however, I wanted to update part of the answer https://stackoverflow.com/users/541038/joran-beasley gave, or at least what worked for me.
Using python3 (3.7.3), I had to modify his first code snippet as follows:
import os
def has_folders(path_to_parent):
for fname in os.listdir(path_to_parent):
if os.path.isdir(os.path.join(path_to_parent, fname)):
yield os.path.join(path_to_parent, fname)
print(list(has_folders("/repo/output")))
Further progress on narrowing to "does given directory contain any directory" results in code like:
import os
def folders_in(path_to_parent):
for fname in os.listdir(path_to_parent):
if os.path.isdir(os.path.join(path_to_parent, fname)):
yield os.path.join(path_to_parent, fname)
def has_folders(path_to_parent):
folders = list(folders_in(path_to_parent))
return len(folders) != 0
print(has_folders("the/path/to/parent"))
The result of this code should be True or False

How to move to one folder back in python

Actually need to go some path and execute some command and below is the code
code:
import os
present_working_directory = '/home/Desktop/folder'
presently i am in folder
if some_condition == true :
change_path = "nodes/hellofolder"
os.chdir(change_path)
print os.getcwd()
if another_condition == true:
change_another_path = "nodes"
os.chdir(change_another_path)
print os.getcwd()
**Result**:
'/home/Desktop/folder/nodes/hellofolder'
python: [Errno 1] No such file or directory
Actually whats happening here is when i first used os.chdir() the directory has changed to
'/home/Desktop/folder/nodes/hellofolder',
but for the second one i need to run a file by moving to one folder back that is
'/home/Desktop/folder/nodes'
So can anyone let me how to move one folder back in python
Just like you would in the shell.
os.chdir("../nodes")
Here is a very platform independent way to do it.
In [1]: os.getcwd()
Out[1]: '/Users/user/Dropbox/temp'
In [2]: os.path.normpath(os.getcwd() + os.sep + os.pardir)
Out[2]: '/Users/user/Dropbox/'
Then you have the path, and you can chdir or whatever with it.
Just call
os.chdir('..')
the same as in any other language :)
Exact answer for your question is os.chdir('../')
Use case:
Folder1:
sub-folder1:(you want to navigate here)
Folder2:
sub-folde2:(you are here)
To navigate to sub-folder1 from sub-folder2, you need to write like this
"../Folder1/sub-folder1/"
then, put it in os.chdir("../Folder1/sub-folder1/").
think about using absolute paths
import os
pwd = '/home/Desktop/folder'
if some_condition == true :
path = os.path.join(pwd, "nodes/hellofolder")
os.chdir(path)
print os.getcwd()
if another_condition == true:
path = os.path.join(pwd, "nodes")
os.chdir(path)
print os.getcwd()
My problem was fixed with this command
first import os and after add
os.path.normpath(os.path.abspath(__file__) + os.sep + os.pardir)
The answers mentioned above are correct. The following is more a
It usually happens when your Python script is in a nested directory and you want to go one level up from the current working directory to maybe let's say load a file.
The idea is to simply reformat the path string and prefix it with a '../'. So an example would be.
'../current_directory/' + filename
This format is similar to when used in a terminal. Whenever in doubt fire up a terminal and experiment with some commands. The format is reflected in the programming language.
Define this function in your script and call it whenever you want to go back just by one folder:
import os
def dirback():
m = os.getcwd()
n = m.rfind("\\")
d = m[0: n+1]
os.chdir(d)
return None

Python: problem with tiny script to delete files

I have a project that used to be under SVN, but now I'm moving it to Mercurial, so I want to clear out all the .svn files.
It's a little too big to do it by hand, so I decided to write a python script to do it. But it isn't working.
def cleandir(dir_path):
print "Cleaning %s\n" % dir_path
toDelete = []
files = os.listdir(dir_path)
for filedir in files:
print "considering %s" % filedir
# continue
if filedir == '.' or filedir == '..':
print "skipping %s" % filedir
continue
path = dir_path + os.sep + filedir
if os.path.isdir(path):
cleandir(path)
else:
print "not dir: %s" % path
if 'svn' in filedir:
toDelete.append(path)
print "Files to be deleted:"
for candidate in toDelete:
print candidate
print "Delete all? [y|n]"
choice = raw_input()
if choice == 'y':
for filedir in toDelete:
if os.path.isdir(filedir):
os.rmdir(filedir)
else:
os.unlink(filedir)
exit()
if __name__ == "__main__":
cleandir(dir)
The print statements show that it's only "considering" the filedirs whose names start with ".". However, if I uncomment the continue statement, all the filedirs are "considered". Why is this?
Or is there some other utility that already exists to recursively de-SVN-ify a directory tree?
At the very least you should not re-invent the wheel for recursive directory traversal and just use os.walk.
This doesn't answer your Python question, but there's an easier way to do what you want: svn export will write your tree of files some place new without all the .svn directories.
The reason 'continue' shows all the folders being considered is because exit() is being called at the end of the function. The call to exit() will exit Python after the first directory is searched. If you change it to 'return' your function will be called recursively.
Also os.listdir does not return '.' or '..' so you don't need a check or any continue statements.
:-)
Davy
I have a project that used to be under SVN, but now I'm moving it to Mercurial, so I want to clear out all the .svn files.
Not to side step your question here (and I know it's been answered, correctly no less) but if you want to export your source from Mercurial, you should use the 'export' command of SVN.... You don't need to manually (or pragmatically) remove all of the .svn folders....
(This is mainly for others' that come up this post looking how to do this)
Also, there are SVN to Mercurial importers....

Categories

Resources