Python终端脚本访问含空格目录触发FileNotFoundError的问题咨询
解决Python脚本处理带空格目录路径的问题
先看你的错误信息:FileNotFoundError: [Errno 2] No such file or directory: '/Users/ali/asd\\ copy\\ 4',这里的\\是关键——这说明输入路径里多了不必要的转义字符,导致系统识别不了正确的目录。
问题根源
当你在终端输入带空格的路径时,如果不用引号包裹,终端会自动把空格转义成\ (比如你输入/Users/ali/asd copy 4,终端会变成/Users/ali/asd\ copy\ 4),而Python的input()函数会直接读取这些反斜杠,把它们当成路径字符串的一部分,最终os.path.abspath处理后就得到了带\\的错误路径,自然找不到目标目录。
两种解决方案
方案1:输入时用引号包裹路径
最简单的办法就是在输入带空格的路径时,用单引号或双引号把路径括起来,比如:
'/Users/ali/asd copy 4'
或者
"/Users/ali/asd copy 4"
这样input()会直接读取到正确的带空格的路径字符串,不会带多余的反斜杠,os.chdir就能正常切换目录了。
方案2:在脚本中自动处理转义字符
如果你不想每次输入都加引号,可以在脚本里对输入的路径做处理,把多余的反斜杠去掉:
修改获取路径的那一行代码:
folderPath = input().replace('\\', '')
修改后的完整脚本如下:
#! /usr/bin/env python3 import os # -- Change working directory. def newWorkingDirectory(): wd = os.getcwd() print('Current working directory is:', wd) print('Enter directory path.') folderPath = input().replace('\\', '') os.chdir(os.path.abspath(folderPath)) wd = os.getcwd() print('Current working directory is:', wd) newWorkingDirectory()
这个方法会自动移除输入字符串里的反斜杠,还原成正确的带空格路径。
额外优化:添加错误处理
为了让脚本更健壮,建议加上异常处理,避免输入错误路径时直接崩溃,给用户友好提示:
#! /usr/bin/env python3 import os # -- Change working directory. def newWorkingDirectory(): wd = os.getcwd() print('Current working directory is:', wd) print('Enter directory path.') folderPath = input().replace('\\', '') target_path = os.path.abspath(folderPath) try: os.chdir(target_path) wd = os.getcwd() print('Current working directory is:', wd) except FileNotFoundError: print(f"Error: 目录 '{target_path}' 不存在,请检查路径是否正确。") except PermissionError: print(f"Error: 没有权限访问目录 '{target_path}'。") except Exception as e: print(f"发生未知错误: {str(e)}") newWorkingDirectory()
测试验证
修改后,不管你是输入带引号的路径,还是直接输入终端自动转义后的路径(比如/Users/ali/asd\ copy\ 4),脚本都能正确识别并切换到目标目录。
内容的提问来源于stack exchange,提问作者Ali Elsokary
相关产品推荐
相关产品推荐

