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
Related
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)
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
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
When I start program like this
python Script.py
abspath return sth like that
os.path.abspath("../../house/kitchen") == "/ex1/ex2/house/kitchen"
But when i start like this i got
python ex3/Script.py
os.path.abspath("../../house/kitchen") == "/house/kitchen"
I think i need to set working place to place where is script but how to do that.
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
This solved my problem
When given a relative path argument, abspath starts from your current directory, not the current directory of the script, so if your current directory changes the output changes.
I chrooted directory using following commands:
os.chroot("/mydir")
How to return to directory to previous - before chrooting?
Maybe it is possible to unchroot directory?
SOLUTION:
Thanks to Phihag. I found a solution. Simple example:
import os
os.mkdir('/tmp/new_dir')
dir1 = os.open('.', os.O_RDONLY)
dir2 = os.open('/tmp/new_dir', os.O_RDONLY)
os.getcwd() # we are in 'tmp'
os.chroot('/tmp/new_dir') # chrooting 'new_dir' directory
os.fchdir(dir2)
os.getcwd() # we are in chrooted directory, but path is '/'. It's OK.
os.fchdir(dir1)
os.getcwd() # we came back to not chrooted 'tmp' directory
os.close(dir1)
os.close(dir2)
More info
If you haven't changed your current working directory, you can simply call
os.chroot('../..') # Add '../' as needed
Of course, this requires the CAP_SYS_CHROOT capability (usually only given to root).
If you have changed your working directory, you can still escape, but it's harder:
os.mkdir('tmp')
os.chroot('tmp')
os.chdir('../../') # Add '../' as needed
os.chroot('.')
If chroot changes the current working directory, you can get around that by opening the directory, and using fchdir to go back.
Of course, if you intend to go out of a chroot in the course of a normal program (i.e. not a demonstration or security exploit), you should rethink your program. First of all, do you really need to escape the chroot? Why can't you just copy the required info into it beforehand?
Also, consider using a second process that stays outside of the chroot and answers to the requests of the chrooted one.