user1118142
user1118142

Reputation: 43

os.chdir() is not working in mac

I am writing a python script to take user input and create directory and change to new directory. However when I invoke os.chdir() and os.getcwd() doesn't work as expected. (Mac OS - linux)

Is there any equivalent to os.chdir()

#!/usr/bin/env python

import os
import sys

# Create a directory
directoryName = raw_input('Enter new directory name: ')
cmdToExecute = 'mkdir ' + directoryName
print cmdToExecute
os.popen(cmdToExecute)

# Change Directory
directoryPath = os.getenv('PWD')
directoryPath = directoryPath + '/' + directoryName 
os.chdir(directoryPath)

Upvotes: 0

Views: 10929

Answers (1)

Hackaholic
Hackaholic

Reputation: 19743

Replace

os.chdir(cmdToExecute)

with:

os.chdir(directoryPath)

you can use os.path.join for joining paths:

directoryPath = os.path.join(directoryPath, directoryName)

this is working fine on my system:

import os
import sys

# Create a directory
directoryName = raw_input('Enter new directory name: ')
cmdToExecute = 'mkdir ' + directoryName
print cmdToExecute
os.popen(cmdToExecute)

# Change Directory
directoryPath = os.getenv('PWD')
directoryPath = os.path.join(directoryPath, directoryName)
os.chdir(directoryPath)
print os.getcwd()

output:

Beagle:titanic_machine_learning kumarshubham$ python test.py
Enter new directory name: test
mkdir test
/Users/kumarshubham/titanic_machine_learning/test

Upvotes: 4

Related Questions