Python中os.chdir切换目录触发FileNotFoundError的解决咨询
问题解决:os.chdir切换目录抛出FileNotFoundError
错误原因
当前工作目录为C:\Users\užívateľ\Desktop\File Manager\File Manager\task\module\root_folder,你输入指令cd task后截取得到的task是当前目录的祖父目录(即module目录的父目录),而非当前目录的子目录。直接执行os.chdir("task")会在当前目录下查找名为task的文件夹,自然找不到,因此触发报错。
对应两种期望输出的修改方案
方案1:切换到指定绝对路径
修改路径构造逻辑,动态生成目标task目录的正确路径:
import os command = "cd task" # 示例输入指令 if command.startswith("cd"): command = command[3:] # 从当前目录向上回溯两级,定位到目标task目录 target_path = os.path.abspath(os.path.join(os.getcwd(), "../..")) os.chdir(target_path) print(os.getcwd()) # 输出:C:\Users\užívateľ\Desktop\File Manager\File Manager\task
方案2:输出相对于原目录的相对路径
如果需要切换目录后输出task(相对路径),可以用os.path.relpath计算相对路径:
import os command = "cd task" # 示例输入指令 original_dir = os.getcwd() # 保存原工作目录 if command.startswith("cd"): command = command[3:] target_path = os.path.abspath(os.path.join(original_dir, "../..")) os.chdir(target_path) # 计算并输出相对于原目录的相对路径 print(os.path.relpath(os.getcwd(), original_dir)) # 输出:task
内容的提问来源于stack exchange,提问作者Rastislav
相关产品推荐
相关产品推荐

