systmao 发表于 2020-8-3 21:15:08

systmao 发表于 2020-8-3 21:19:03

Twilight6 发表于 2020-8-3 21:20:10

帖子的复制代码那个怎么搞出来的~

点击编辑器的 <> 按钮

不能懒 发表于 2020-8-3 21:20:17

复制代码直接点击<>,然后把你的代码复制进去提交就可以了

systmao 发表于 2020-8-3 21:23:03

Twilight6 发表于 2020-8-3 21:24:34

systmao 发表于 2020-8-3 21:23
谢谢,已经把代码贴上来了。

哈哈 我刚刚已经帮你重新编辑了{:10_245:}

systmao 发表于 2020-8-3 21:25:48

Twilight6 发表于 2020-8-3 21:29:16

systmao 发表于 2020-8-3 21:25
哈哈哈哈哈哈 怪不得我说怎么多出来一个code


代码改成这样试试看:

import openpyxl
import os
def search_file(start_dir,target):
    os.chdir(start_dir)
    for each_file in os.listdir(os.curdir):
      ext = os.path.splitext(each_file)
      if ext in target:
            wb = openpyxl.load_workbook(each_file)
            ws = wb['Sheet1']
            file_dict=ws['C4'].value
            #找到excel表格,把每个excle中的C4值添加进字典
      if os.path.isdir(each_file):
            search_file(each_file,target)#递归调用
            os.chdir(os.pardir)#递归调用后,返回上一层目录

start_dir = r'E:\\Z\\test'
file_dict=dict()
target = ['.xlsx','.xlx']

search_file(start_dir,target)

systmao 发表于 2020-8-3 22:14:54

systmao 发表于 2020-8-3 22:33:47

Twilight6 发表于 2020-8-4 00:06:13

本帖最后由 Twilight6 于 2020-8-4 00:39 编辑

systmao 发表于 2020-8-3 22:33
我尝试了你这个代码,但是这个代码没解决问题。
就是我想要得到 文件名和excle的数值的字典
但是 您给 ...


那这样就好了吧,只不过这个代码在文件夹里面有多个 excel 文件值会被之前的覆盖,只会保留最后一次读取到的文件数据

import openpyxl
import os
def search_file(start_dir,target):
    os.chdir(start_dir)
    file_name = start_dir.rsplit('\\',1)
    for each_file in os.listdir(os.curdir):
      ext = os.path.splitext(each_file)
      if ext in target:
            wb = openpyxl.load_workbook(each_file)
            ws = wb['Sheet1']
            file_dict=ws['C4'].value
            
      if os.path.isdir(each_file):
            search_file(each_file,target)
            os.chdir(os.pardir)

start_dir = r'E:\\Z\\test'
file_dict=dict()
target = ['.xlsx','.xlx']

search_file(start_dir,target)
页: [1]
查看完整版本: 递归函数中的全局变量问题