Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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

share|improve this question
    
This is kind of confusing are you trying to get the directory that the script is in or what post your code with the question – Serial May 5 '13 at 23:48
    
Yes. The directory that my script is in. – user2353003 May 5 '13 at 23:52
up vote 1 down vote accepted

For current working directory:

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

For the script directory:

import os
sdir=os.path.dirname(os.path.abspath(__file__)).split(os.sep)[-1]
print sdir
share|improve this answer

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
share|improve this answer

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

os.getcwd()                   # => '/Users/jon'
os.path.basename(os.getcwd()) # => 'jon'
share|improve this answer
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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.