iT邦幫忙

1

額外請教一下怎麼讀資料夾內所有EXCEL檔案並讓他跑模型

小弟撰寫讀資料夾內EXCEL檔案,就是發現他只會讀一個檔案進去,所以請教各位大大有何方法處理,另外它額外工作表,我希望舉例就工作表1數值工做表1,工作表2數值就工作表2,煩請大大好心能留個程式碼謝謝,因為嘗試過網路上作法發現只會讀一個檔案進去==
path = '檔案路徑'
fs_all_file = os.listdir(path)
complete_path = []
for file_name in fs_all_file:
complete_path.append(os.path.join(path, file_name))

combin_list = []
for cmp in complete_path:
total_data = pd.DataFrame()
for i in file_name:
data = pd.read_excel(cmp)
total_data = pd.concat([total_data ,data],sort=True)

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
mackuo
iT邦研究生 2 級 ‧ 2022-08-03 12:06:15
最佳解答

2022/08/05 更新:
樓主原先的描述與實際狀況有點不同,實做時也出了一點問題。
樓主有私訊,並給了檔案。

我來重新定義一下問題:
樓主有n個excel檔案,每個檔案中都有time、X、Y、Z工作表。
樓主想要把每個excel檔案中「相同名稱」的工作表讀出來,並整合成同一個dataframe,
然後再來做後續的處理。

這邊要提醒一下,樓主給的檔案,資料都沒設定欄位名稱。

以下修正程式碼:

讀取目錄下所有的xls或xlsx的附檔名檔案:

import pandas as pd
import os

path = os.getcwd()
# List files:
files = os.listdir(path)
print(files)
files_xlsx = [f for f in files if f[-4:] == "xlsx"]
files_xls = [f for f in files if f[-3:] == "xls"]
files_xls.extend(files_xlsx)
for i, element in enumerate(files_xls):
    print(i, element)
print(len(files_xls))

print(files_xls)

https://ithelp.ithome.com.tw/upload/images/20220805/20122335ZfVezlIdkd.png

import warnings
sh_list = ['time', 'X', 'Y', 'Z']

for s in sh_list:
    df = pd.DataFrame()
    print(f'工作表變數:{s}')
    for f in files_xls:
        data = pd.read_excel(f, sheet_name=s)        
        warnings.simplefilter("ignore") #不顯示讀檔驗證警告
        print(f'檔案名稱:{f},工作表{s}的原始資料筆數:{len(data)}')

        df = df.append(data, ignore_index=True) # 將所有檔案中相同名稱的工作表dataframe合併
    print(f'dataframe_{s}的總資料筆數:{len(df)}')
    
    
    exec('{} = df.copy()'.format('df_'+s)) # 將合併好的工作表dataframe存到一個新的名稱如df_time

https://ithelp.ithome.com.tw/upload/images/20220805/201223358VEybW8jza.png
https://ithelp.ithome.com.tw/upload/images/20220805/201223359Vf5NtTSux.png
https://ithelp.ithome.com.tw/upload/images/20220805/20122335C5cbFbkAb1.png
https://ithelp.ithome.com.tw/upload/images/20220805/20122335xR18jwIyMI.png
https://ithelp.ithome.com.tw/upload/images/20220805/20122335hjBBtHTbOV.png

看更多先前的回應...收起先前的回應...
bobfriend iT邦新手 5 級 ‧ 2022-08-03 15:11:32 檢舉

大大那資料夾路徑放哪邊好?

mackuo iT邦研究生 2 級 ‧ 2022-08-03 15:29:40 檢舉

excel檔案就放在你寫的程式碼的py或ipny同一個目錄下喔。

bobfriend iT邦新手 5 級 ‧ 2022-08-03 16:07:52 檢舉

是指我這段嗎?
path = '檔案路徑'
fs_all_file = os.listdir(path)
complete_path = []
for file_name in fs_all_file:
complete_path.append(os.path.join(path, file_name))

bobfriend iT邦新手 5 級 ‧ 2022-08-03 17:19:44 檢舉

name 'target_xls' is not defined還有大大請教23行 我跑出來是這樣?

bobfriend iT邦新手 5 級 ‧ 2022-08-03 17:21:31 檢舉

還是大大知道我有標籤值所以才幫忙給這行?

bobfriend iT邦新手 5 級 ‧ 2022-08-03 17:22:07 檢舉

for f in target_xls這行出問題

mackuo iT邦研究生 2 級 ‧ 2022-08-04 09:08:23 檢舉

不好意思,因為是從之前自己的程式碼抽出來的,原始程式還有做別的處理。
程式碼已有修正,請改成for f in files_xls:

bobfriend iT邦新手 5 級 ‧ 2022-08-04 16:04:09 檢舉

謝謝我再試試

2
mantissa23bit
iT邦新手 4 級 ‧ 2022-08-03 09:11:14

提供讀取所有資料夾內檔案的程式碼給你參考
C#

DirectoryInfo directInfo = new DirectoryInfo("資料夾路徑");
foreach (FileInfo file in directInfo.GetFiles())//取得資料夾中的每個檔案
{
    if (!file.FullName.Contains(".xls"))//檔案格式不是.xls就讀下一個檔案
        continue;
    *你處理EXCEL的程式碼;*
}

我要發表回答

立即登入回答