鱼C论坛

 找回密码
 立即注册
查看: 1357|回复: 2

[已解决]python遍历文件夹下的子文件夹,不继续下一级

[复制链接]
发表于 2022-6-13 15:30:38 | 显示全部楼层 |阅读模式
6鱼币
  1. from docx import Document
  2. from docx.shared import Inches
  3. import os
  4. from PIL import Image

  5. doc = Document(r"C:\Users\liqian6\Desktop\python\digao\word模板.docx")
  6. fold = r"C:\\Users\liqian6\Desktop\python\digao"

  7. for root, dirs, files in os.walk(fold):

  8.         for i in range(0,len(files)):
  9.             doc=Document()
  10.             doc_name=os.path.basename(files[i])
  11.             print(doc_name)
复制代码


想要获取fold文件夹的子文件夹,但不想获取子文件夹内的文件,上面的程序是获取了所有的文件,想请教一下如何操作?大佬能加些注释就更好了,小白跪谢555
(这是循环的第一层,假设fold里有两个子文件夹,子文件夹含多个文件。目的是想对大文件夹里的每个小文件夹进行循环,把每个子文件夹中的图片插入word模板里,最终分别形成两个word
最佳答案
2022-6-13 15:30:39
  1. from docx import Document
  2. from docx.shared import Inches
  3. import os
  4. from PIL import Image

  5. doc = Document(r"C:\Users\liqian6\Desktop\python\digao\word模板.docx")
  6. fold = r"C:\\Users\liqian6\Desktop\python\digao"

  7. for each in os . listdir(fold):
  8.     x = os . path . join(fold , each)
  9.     if os . path . isdir(x):
  10.         print(each)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-6-13 15:30:39 | 显示全部楼层    本楼为最佳答案   
  1. from docx import Document
  2. from docx.shared import Inches
  3. import os
  4. from PIL import Image

  5. doc = Document(r"C:\Users\liqian6\Desktop\python\digao\word模板.docx")
  6. fold = r"C:\\Users\liqian6\Desktop\python\digao"

  7. for each in os . listdir(fold):
  8.     x = os . path . join(fold , each)
  9.     if os . path . isdir(x):
  10.         print(each)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-6-17 08:35:09 | 显示全部楼层
本帖最后由 suchocolate 于 2022-6-17 13:25 编辑

方式一:
  1. dirs = next(os.walk(fold))[1]
复制代码


方式二:
  1. dirs = [f for f in os.listdir(fold) if os.path.isdir(f)]
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-24 07:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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