我是 Python 的新手,我第一次在堆栈溢出中发布问题。请帮助解决问题。
我的主目录是“E:\Data Science\Macros\ZBILL_Dump”,包含按月的文件夹,每个文件夹包含按日期的 excel 数据。
我能够从单个文件夹中提取数据:
import os
import pandas as pd
import numpy as np
# Find file names in the specified directory
loc = 'E:\Data Science\Macros\ZBILL_Dump\Apr17\\'
files = os.listdir(loc)
# Find the ONLY Excel files
files_xlsx = [f for f in files if f[-4:] == 'xlsx']
# Create empty dataframe and read in new data
zbill = pd.DataFrame()
for f in files_xlsx:
New_data = pd.read_excel(os.path.normpath(loc + f), 'Sheet1')
zbill = zbill.append(New_data)
zbill.head()
我试图从我的主目录中提取数据,即包含许多子文件夹的“ZBILL_Dump”,但我做不到。请有人帮助我。
非常感谢。
请您参考如下方法:
你可以使用 glob。
import glob
import pandas as pd
# grab excel files only
pattern = 'E:\Data Science\Macros\ZBILL_Dump\Apr17\\*.xlsx'
# Save all file matches: xlsx_files
xlsx_files = glob.glob(pattern)
# Create an empty list: frames
frames = []
# Iterate over csv_files
for file in xlsx_files:
# Read xlsx into a DataFrame
df = pd.read_xlsx(file)
# Append df to frames
frames.append(df)
# Concatenate frames into dataframe
zbill = pd.concat(frames)
如果您想查看不同的子目录,您可以使用正则表达式。使用'filepath/*/*.xlsx' 搜索下一级。更多信息在这里 https://docs.python.org/3/library/glob.html
