os.chdir() 在 mac 中不起作用

os.chdir() is not working in mac

我正在编写一个 python 脚本来获取用户输入并创建目录并切换到新目录。但是,当我调用 os.chdir() 和 os.getcwd() 时,它不会按预期工作。 (Mac OS - linux)

有没有等价于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)

替换

os.chdir(cmdToExecute)

与:

os.chdir(directoryPath)

您可以使用 os.path.join 加入路径:

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

这在我的系统上运行良好:

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()

输出:

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