python更改当前目录_如何从python脚本更改当前目录?

I'm trying to implement my own version of the 'cd' command that presents the user with a list of hard-coded directories to choose from, and the user has to enter a number corresponding to an entry in the list. The program, named my_cd.py for now, should then effectively 'cd' the user to the chosen directory. Example of how this should work:

/some/directory

$ my_cd.py

1) ~

2) /bin/

3) /usr

Enter menu selection, or q to quit: 2

/bin

$

Currently, I'm trying to 'cd' using os.chdir('dir'). However, this doesn't work, probably because my_cd.py is kicked off in its own child process. I tried wrapping the call to my_cd.py in a sourced bash script named my_cd.sh:

#! /bin/bash

function my_cd() {

/path/to/my_cd.py

}

/some/directory

$ . my_cd.sh

$ my_cd

... shows list of dirs, but doesn't 'cd' in the interactive shell

Any ideas on how I can get this to work? Is it possible to change my interactive shell's current directory from a python script?

解决方案

This can't be done. Changes to the working directory are not visible to parent processes. At best you could have the Python script print the directory to change to, then have the sourced script actually change to that directory.

### 回答1: 可以使用Python内置的os模块来更改当前工作目录到上级目录,具体的方法是: ```python import os os.chdir('..') # 将当前工作目录更改为上级目录 ``` 其中 `chdir()` 方法可以接受一个相对路径或绝对路径作为参数,将当前工作目录更改为指定的目录。在这个例子中,通过传递 `'..'` 作为参数,将当前工作目录更改为上级目录。 ### 回答2: 要将当前工作目录更改为上级目录,可以使用Python中的os模块。 首先,需要导入os模块: import os 然后,可以使用os模块中的chdir()函数来更改当前工作目录。chdir()函数接受一个参数,即要更改的目录路径。 如果想要将当前工作目录更改为上级目录,可以使用os.path模块的abspath()函数获取当前脚本所在的绝对路径,然后使用os.path模块的dirname()函数获取上级目录的路径。 具体代码如下: import os # 获取当前脚本所在的绝对路径 current_path = os.path.abspath(__file__) # 获取上级目录的路径 parent_path = os.path.dirname(current_path) # 更改当前工作目录为上级目录 os.chdir(parent_path) 注意,__file__是Python内置变量,表示当前脚本文件的路径。 现在,当前工作目录已经更改为上级目录了。可以通过调用os.getcwd()函数来验证当前工作目录是否已更改。 完整代码如下: import os current_path = os.path.abspath(__file__) parent_path = os.path.dirname(current_path) os.chdir(parent_path) # 验证当前工作目录是否已更改 print("当前工作目录:", os.getcwd()) ### 回答3: 要更改Python的当前工作目录到上级目录,可以使用`os`模块中的`chdir()`函数。 `chdir()`函数用于更改当前工作目录,接受一个字符串类型的参数,表示要切换到的目录路径。 首先,我们需要导入`os`模块: ```python import os ``` 然后,使用`os.chdir()`函数,并将当前工作目录的上级目录路径作为参数传递给它: ```python os.chdir("..") ``` 这样,当前工作目录就会更改为上级目录。 完整的代码如下: ```python import os os.chdir("..") ``` 需要注意的是,如果你当前的工作目录是根目录,执行`os.chdir("..")`会出错,因为根目录没有上级目录。所以,在执行这段代码之前,最好先判断当前工作目录是否为根目录: ```python import os if os.getcwd() != '/': os.chdir("..") ``` 以上就是使用Python将当前工作目录更改为上级目录的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值