|  | 
 
| 
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  复制代码import os
def search_file(start_dir,target):
    os.chdir(start_dir)
    all_files = os.listdir(os.curdir)
    for each_file in all_files:
        if each_file == target:
            print(os.getcwd() + os.sep + each_file)
        if os.path.isdir(each_file):
            search_file(each_file,target)
            os.chdir(os.pardir)
    
start_dir = input('请输入要查找的目录')
target = input('请输入目标文件名')
search_file(start_dir,target)
为什么我的代码运行后提示
  对了一遍没差呀   
 
 复制代码请输入要查找的目录'G:\\Python'
请输入目标文件名'something.txt'
Traceback (most recent call last):
  File "G:/Python/search_file.py", line 15, in <module>
    search_file(start_dir,target)
  File "G:/Python/search_file.py", line 4, in search_file
    os.chdir(start_dir)
OSError: [WinError 123] 文件名、目录名或卷标语法不正确。: "'G:\\\\Python'"
>>> 
 本帖最后由 逃兵 于 2021-1-20 16:09 编辑 
input是将你输入的字符转化为字符串 
如果你输入的文字中带引号,引号也会成为字符串中的字符 
例: 
输入:张三 
name = '张三' 
输入:'张三' 
name = "'张三'"
 
你报错的最后一行可以看到
 
OSError: [WinError 123] 文件名、目录名或卷标语法不正确。: "'G:\\\\Python'"
 
带引号的字符串"'G:\\\\Python'"错误,应该为"G:\\\\Python" | 
 |