Python level up directory

Python — change given directory one level above or below

but need to change activeworkbook path: I would want Using Excel 365 VBA Solution 1: As the path may not be the current working directory you need to extract the path from the string. Find the last and read all characters to the left: If you are working around the current directory will jump you up one level, the new path can be returned by . But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath so that you could do something like this: Solution 4: In Python 3.4 pathlib was introduced: It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.

Python — change given directory one level above or below

is there a way to get one level above or below directory from the one that is given? For example ‘/a/b/c/’ directory was entered in a function.

lvl_down = '/a/b/' lvl_up = '/a/b/c/d/' 

I think you can do it using ‘re’ module (at least with one level below directory), but maybe there is more simple and better way to do it without regex?

I have no idea, how the function should know, that you want to go in directory d :

#!/usr/bin/python import os.path def lvl_down(path): return os.path.split(path)[0] def lvl_up(path, up_dir): return os.path.join(path, up_dir) print(lvl_down('a/b/c')) # prints a/b print(lvl_up('a/b/c','d')) # prints a/b/c/d 

Note: Had another solution before, but os.path is a much better one.

Methods for manipulating paths can be found in the modules os and os.path .

os.path.join — Join one or more path components intelligently.

os.path.split — Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that.

os.path.isdir — Return True if path is an existing directory.

os.listdir — Return a list containing the names of the entries in the directory given by path .

def parentDir(dir): return os.path.split(dir)[0] def childDirs(dir): possibleChildren = [os.path.join(dir, file) for file in os.listdir(dir)] return [file for file in possibleChildren if os.path.isdir(file)] 

First of all, if the path given ends in a slash, you should always remove it with a slice. With that said, here’s how to get the parent directory of a path:

>>> import os.path >>> p = '/usr/local' >>> os.path.dirname(p) '/usr' 

To go down, just append the name to the variable like so:

>>> head = '/usr/local' >>> rest = 'include' >>> os.path.join(head, rest) '/usr/local/include' 

Python — change given directory one level above or below, os.path.split — Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. os.path.isdir — Return True if path is an existing directory. os.listdir — Return a list containing the names of the entries in the directory given by path. Code sampledef lvl_up(path, up_dir):return os.path.join(path, up_dir)print(lvl_down(‘a/b/c’)) # prints a/bprint(lvl_up(‘a/b/c’,’d’)) # prints a/b/c/dFeedback

Читайте также:  Открытие нескольких файлов python

Using Python’s os.path, how do I go up one directory?

I recently upgrade Django from v1.3.1 to v1.4.

In my old settings.py I have

TEMPLATE_DIRS = ( os.path.join(os.path.dirname( __file__ ), 'templates').replace('\\', '/'), # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) 

This will point to /Users/hobbes3/Sites/mysite/templates , but because Django v1.4 moved the project folder to the same level as the app folders, my settings.py file is now in /Users/hobbes3/Sites/mysite/mysite/ instead of /Users/hobbes3/Sites/mysite/ .

So actually my question is now twofold:

  1. How do I use os.path to look at a directory one level above from __file__ . In other words, I want /Users/hobbes3/Sites/mysite/mysite/settings.py to find /Users/hobbes3/Sites/mysite/templates using relative paths .
  2. Should I be keeping the template folder (which has cross-app templates, like admin , registration , etc.) at the project /User/hobbes3/Sites/mysite level or at /User/hobbes3/Sites/mysite/mysite ?
os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates')) 

As far as where the templates folder should go, I don’t know since Django 1.4 just came out and I haven’t looked at it yet. You should probably ask another question on SE to solve that issue.

You can also use normpath to clean up the path, rather than abspath . However, in this situation, Django expects an absolute path rather than a relative path .

For cross platform compatability, use os.pardir instead of ‘..’ .

To get the folder of a file just use:

To get a folder up just use os.path.dirname again

os.path.dirname(os.path.dirname(path)) 

You might want to check if __file__ is a symlink:

if os.path.islink(__file__): path = os.readlink (__file__) 

If you are using Python 3.4 or newer, a convenient way to move up multiple directories is pathlib :

from pathlib import Path full_path = "path/to/directory" str(Path(full_path).parents[0]) # "path/to" str(Path(full_path).parents[1]) # "path" str(Path(full_path).parents[2]) # "." 
BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' ) 

Using Python’s os.path, how do I go up one directory?, Go up a level from the work directory. import os os.path.dirname(os.getcwd()) or from the current directory. import os os.path.dirname(‘current path’) Share. Follow answered Aug 24, 2020 at 11:00. Julio CamPlaz Julio CamPlaz. 798 6 6 silver badges 18 18 bronze badges. Add a …

Читайте также:  Java как сделать package

Go up one folder level

I have a Macro that gets sub folder data. However I also want something from the main folder.

I looked at how to get current working directory using vba ? but need to change activeworkbook path:

Application.ActiveWorkbook.Path might be "c:\parent\subfolder" 

As the path may not be the current working directory you need to extract the path from the string.

Find the last \ and read all characters to the left:

ParentPath = Left$(Path, InStrRev(Path, "\")) 

If you are working around the current directory ChDir «..» will jump you up one level, the new path can be returned by CurrDir .

The most reliable way to do this is to use the Scripting.FileSystemObject. It has a method that will get the parent folder without trying to parse it:

With CreateObject("Scripting.FileSystemObject") Debug.Print .GetParentFolderName(Application.ActiveWorkbook.Path) End With 
Dim WbDir As String Dim OneLvlUpDir As String 'get current WorkBook directory WbDir = Application.ActiveWorkbook.Path 'get directory one level up ChDir WbDir ChDir ".." 'print new working directory and save as string. Use as needed. Debug.Print CurDir() OneLvlUpDir = CurDir() 

I think you mean this solution:

Sub t() Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") MsgBox "ThisWorkbook.Path = " & ThisWorkbook.Path & vbLf & _ "Path one folder down = " & fso.GetFolder(ThisWorkbook.Path & "\." & "NewFolder").Path Set fso = Nothing End Sub 

Vba — Go up one folder level, As the path may not be the current working directory you need to extract the path from the string. Find the last \ and read all characters to the left: ParentPath = Left$ (Path, InStrRev (Path, «\»)) If you are working around the current directory ChDir «..» will jump you up one level, the new path can be returned by …

Moving up one directory in Python

Is there a simple way to move up one directory in python using a single line of code? Something similar to cd .. in command line

>>> import os >>> print os.path.abspath(os.curdir) C:\Python27 >>> os.chdir("..") >>> print os.path.abspath(os.curdir) C:\ 

Using os.chdir should work:

Obviously that os.chdir(‘..’) is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath

so that you could do something like this:

>>> from unipath import Path >>> p = Path("/usr/lib/python2.5/gopherlib.py") >>> p.parent Path("/usr/lib/python2.5") >>> p.name Path("gopherlib.py") >>> p.ext '.py' 

In Python 3.4 pathlib was introduced:

>>> from pathlib import Path >>> p = Path('/etc/usr/lib') >>> p PosixPath('/etc/usr/lib') >>> p.parent PosixPath('/etc/usr') 

It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.

Читайте также:  Javascript html css задачи

For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.

Moving up one directory in Python, The use of this function is fairly simple — all you need is your path and number of directories up. print (dir_up (curDir,3)) # print 3 directories above the current one The only minus is that it doesn’t stop on drive letter, it just will show you empty string. Share answered Feb 10, 2020 at 10:48 Radek D 79 9 Add a …

Источник

Python change current directory(up to parent) 3 Examples

Getting the current folder and moving one or several levels up is possible in Python 3 with several different options:

Moving one directory up with os.chdir(«..»)

The most popular way and the one compatible with older python versions is os.chdir(«..»). Below you can find the usage of it:

import os print(os.path.abspath(os.curdir)) os.chdir("..") print(os.path.abspath(os.curdir)) 

You can move several levels up with this syntax:

import os print(os.path.abspath(os.curdir)) os.chdir("../../..") print(os.path.abspath(os.curdir)) 

Moving one directory up with pathlib — p.parent

Another way of working with folders and files was introduced since Python 3.4 — pathlib. It provides methods and information related to files and folders:

  • get parent folder(or parent of the parent)
  • get file name and absolute path
  • get statistics for the file
  • check if the object is a file or a directory
from pathlib import Path p = Path("/home/user/myfile.txt") print(p.parent) print(p.parent.parent) print(p.name) print(p.as_posix()) print(p.stat()) print(p.is_dir()) print(p.is_file()) 

/home/user/
/home
myfile.txt
/home/user/myfile.txt
os.stat_result(st_mode=33204, st_ino=16515537, st_dev=64769, st_nlink=1, st_uid=1000, st_gid=1000, st_size=79152, st_atime=1536731949, st_mtime=1536731949, st_ctime=1536731949)
False
True

Moving up with os.chdir(os.path.dirname(os.getcwd()))

Another way is possible from the module os by using: os.chdir(os.path.dirname(os.getcwd())) . Below you can see the example how to change the working folder from the python script itself:

import os print(os.path.dirname(os.getcwd())) os.chdir(os.path.dirname(os.getcwd())) print(os.path.dirname(os.getcwd())) 

You can move several levels up with this syntax:

import os print(os.path.abspath(os.curdir)) os.chdir("../../..") print(os.path.abspath(os.curdir)) 

Note that once the directory is changed the result with one of this methods than the current folder will be different for the script. In other words:

This code will produce output which is moving up to the root folder:

import os print(os.path.dirname(os.getcwd())) os.chdir(os.path.dirname(os.getcwd())) print(os.path.dirname(os.getcwd())) os.chdir(os.path.dirname(os.getcwd())) print(os.path.dirname(os.getcwd())) os.chdir(os.path.dirname(os.getcwd())) print(os.path.dirname(os.getcwd())) 

/home/user/PycharmProjects/python/test
/home/user/PycharmProjects/python
/home/user/PycharmProjects
/home/user

Python move back one folder

If you want to move back one folder then you can try with:

import os print(os.path.abspath(os.curdir)) print(os.path.normpath(os.getcwd() + os.sep + os.pardir)) print(os.path.abspath(os.curdir)) 
import os print(os.path.abspath(os.curdir)) os.chdir("../python") print(os.path.abspath(os.curdir)) 

By using SoftHints — Python, Linux, Pandas , you agree to our Cookie Policy.

Источник

Оцените статью