Python:汇总保存在不同文件夹中的 xlsx 文件的值
Python: summing up values from xlsx files saved in different folders
假设我有一个包含 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
你的循环似乎是正确的。 os.walk
returns 你,对于迭代中的每个元素,3 个值,下一个目录,当前目录中的 sub-directories,以及当前目录中的文件列表。
在此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
假设我有一个包含 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
你的循环似乎是正确的。 os.walk
returns 你,对于迭代中的每个元素,3 个值,下一个目录,当前目录中的 sub-directories,以及当前目录中的文件列表。
在此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