【问题标题】:Python: summing up values from xlsx files saved in different foldersPython:总结保存在不同文件夹中的 xlsx 文件的值
【发布时间】:2016-04-15 20:11:56
【问题描述】:

假设我有一个包含 20 个子文件夹的主文件夹。每个子文件夹仅包含一个xlsx 文件。我想总结每个xlsx文件的A列中的所有值,从而获得sub folder-sum value配对。

然后,我想重复此操作,次数与主文件夹一样多。

例子:

MAIN FOLDER 1

   SUB FOLDER 1  SUB FOLDER 2

   file1.xlsx    file2.xlsx
   A1 17         A1 20
   A2 32         A2 30
   A3 24         A3 10

相应的结果是:

MAIN FOLDER 1    
sum1 = 17+32+24 = 73 -> Pairing 1= Sub folder 1; 73
sum2 = 20+30+10 = 60 -> Pairing 2= Sub folder 2; 60
...

我已经写了一段代码,但我不确定 for 循环是否正确:

import os
from openpyxl import Workbook

directoryPath=r'C:\Users\MyDir'
os.mkdir(directoryPath)
for root, dirs, files in os.walk(directoryPath): #This confuses me as I don't see how the main folders are differentiated from the sub folders
    for name in files:
        if name.endswith((".xlsx")):

            #summing up 

【问题讨论】:

标签: python excel for-loop directory subdirectory


【解决方案1】:

您的循环似乎是正确的。 os.walk 为迭代中的每个元素返回 3 个值、下一个目录、当前目录中的子目录以及当前目录中的文件列表。

在这个link,你可以阅读os.walk的正确使用方法。

看下面的例子。假设我有以下目录结构:

+---main
|   |   
|   +---sub1
|   |       f2.xls
|   |       
|   \---sub2
|           f1.xls

这基本上是您当前的代码:

for dirName, subdirList, fileList in os.walk(rootDir):
print('Found directory: %s' % dirName)
for fname in fileList:
    print('\t%s' % fname)

在第一个循环中,您遍历主文件夹中的目录。每次迭代都将代表您正在寻找的配对。第二个循环,for fname in fileList,仅列出存储在dirName 中的文件夹中的文件,因此您不能将错误的文件夹和文件配对。其实这是你的代码输出:

Found directory: C:/Users/cr01046/Desktop/main
Found directory: C:/Users/cr01046/Desktop/main\sub1
         f2.xls
Found directory: C:/Users/cr01046/Desktop/main\sub2
         f1.xls

【讨论】:

  • 在我的情况下,file1.xlsx 的总和值需要与子文件夹名称严格相关。与file2.xlsx 等相同。我如何确定 os.walk 不会弄乱配对(子文件夹;总和值)?我不明白您建议的链接中提供的方案,这就是我专门询问的原因。
  • 有了这个循环,你就不能弄乱正确的配对顺序。我已经用一个适当的例子编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2019-10-18
  • 1970-01-01
  • 2018-04-15
  • 2019-12-01
  • 1970-01-01
相关资源
最近更新 更多