2

I am new to python and I am struggling to accomplish a simple ask. I am trying to copy my current directory name and placing it into a variable. I dont need the contents of that directory, or the path to that directory. I just need the name of my current directory to be placed into a variable.

Thank you

user2353003
  • 522
  • 1
  • 7
  • 18

4 Answers4

2

For current working directory, use:

import os
cdir=os.getcwd().split(os.sep)[-1]
print (cdir)

For the script directory, use:

import os
sdir=os.path.dirname(os.path.abspath(__file__)).split(os.sep)[-1]
print (sdir)
MyCarta
  • 808
  • 2
  • 12
  • 37
perreal
  • 94,503
  • 21
  • 155
  • 181
2

As seen in my other answer, you can achieve that this way:

import os
module_dir = os.path.dirname(__file__)  # get current file's directory
Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198
0

Use os.getcwd along with os.path.basename.

os.getcwd()                   # => '/Users/jon'
os.path.basename(os.getcwd()) # => 'jon'
Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69
0
import os
x = cdir=os.getcwd().split(os.sep)[-1]
print x 

this assigns x the directory name and then prints it but you dont have to print it

Serial
  • 7,925
  • 13
  • 52
  • 71