鱼C论坛

 找回密码
 立即注册
查看: 1126|回复: 1

[已解决]这样为什么无法获得正确文件位置

[复制链接]
发表于 2021-7-20 20:32:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
结构如下:
大文件夹:
        1.txt
        文件夹1
                2.txt
                空文件夹
想要获得所有txt文本的路径,正确输出应该是:
大文件夹\1.txt
大文件夹\文件夹1\2.txt
可是却输出了:
大文件夹\文件夹1\2.txt
大文件夹\文件夹1\空文件夹\1.txt
  1. import os
  2. import os.path
  3. key=input('请将该脚本放于待查找的文件夹内,请输入关键字:')
  4. YN=input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):'%key)
  5. os.chdir(r'C:\Users\wind\Desktop\test')
  6. list1=[]
  7. def listtxt(path):
  8.     os.chdir(path)
  9.     for each in os.listdir():
  10.         (a,b)=os.path.splitext(each)
  11.         if b=='.txt':
  12.             list1.append(os.getcwd()+os.sep+each)
  13.         if os.path.isdir(each):
  14.             listtxt(each)
  15. listtxt(r'C:\Users\wind\Desktop\test')
复制代码
最佳答案
2021-7-21 08:51:19

因为你递归 os.chdir 更改了工作目录,忘记返回上一层目录了,在递归函数下面加个 os.chdir('..') 即可

你代码前面的 input 没什么用,因为你想找的是 txt 文件,在你代码上稍微修改了下,参考代码:

  1. import os
  2. import os.path

  3. list1=[]
  4. def listtxt(path):
  5.     os.chdir(path)
  6.     for each in os.listdir():
  7.         (a,b)=os.path.splitext(each)
  8.         if b == '.txt':
  9.             list1.append(os.getcwd()+os.sep+each)
  10.         if os.path.isdir(each):
  11.             listtxt(each)
  12.             os.chdir('..')
  13.             
  14. listtxt(r'C:\Users\wind\Desktop\test')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-7-21 08:51:19 | 显示全部楼层    本楼为最佳答案   

因为你递归 os.chdir 更改了工作目录,忘记返回上一层目录了,在递归函数下面加个 os.chdir('..') 即可

你代码前面的 input 没什么用,因为你想找的是 txt 文件,在你代码上稍微修改了下,参考代码:

  1. import os
  2. import os.path

  3. list1=[]
  4. def listtxt(path):
  5.     os.chdir(path)
  6.     for each in os.listdir():
  7.         (a,b)=os.path.splitext(each)
  8.         if b == '.txt':
  9.             list1.append(os.getcwd()+os.sep+each)
  10.         if os.path.isdir(each):
  11.             listtxt(each)
  12.             os.chdir('..')
  13.             
  14. listtxt(r'C:\Users\wind\Desktop\test')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-21 13:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表