我有 30 個檔案夾(從2021-06-01到2021-06-30),在每個檔案夾中我有 15 個 excel 檔案。目前我分別使用此代碼 30 次
file1= glob.glob('C:/Users/Dell/Downloads/2021-06-01/*')
使檔案file1在處理每一個單個檔案夾(進入15個Excel檔案)的操作運行資料。所以,我可以有file 1來file 30,然后我concat他們做一個單一的檔案。有什么辦法可以自動化這個程序,因為我不想單獨運行這個操作 30 次?我不知道如何為此目的進行回圈以從不同路徑提取檔案。我也有資料,但它們被壓縮在檔案夾內(從2021-06-01到2021-06-30)。所以,一一去那里解壓,然后一一運行操作就很乏味了。我怎樣才能以更簡單的方式實作這兩個目的?我看到搜索解壓操作解決方案,通過我不能做他們,而我也有獲取另一目的,我提及(經歷不同的檔案夾,并在一次提取它們一個接一個,使file 1以file 30一次)我的目錄,如下所示:
- download
-month
-2021-01-01
-AA
-file.zip
-a list of .xlsx file
-BB
-CC
-2021-01-02
-AA
-file.zip
-a list of .xlsx file
-BB
-CC
...........................................................................................................................................................................
-2021-01-30
現在我不想連接這些 xlsx 檔案。我想對這些excel檔案一個一個地運行某個操作,然后將它們連接起來。但是不能這樣做。
uj5u.com熱心網友回復:
這是一個 Python 腳本,它應該適合你:
import os
import shutil
import time
import pandas as pd
def read_csv_or_excel(f):
if f.endswith(".csv"):
df = pd.read_csv(f"{root}/{f}", sep="\t")
if f.endswith(".xlsx"):
df = pd.read_excel(f"{root}/{f}")
return df
for root, dirs, files in os.walk("./questions/69878352/"):
# print(root, dirs, files)
if root.split("/")[-1].startswith("20"):
print(root)
appended = []
dfs = []
for f in files:
if f not in appended:
print(f)
if f.endswith(".csv") or f.endswith(".xlsx"):
dfs.append(read_csv_or_excel(f))
elif f.endswith(".zip"):
shutil.unpack_archive(f"{root}/{f}", f"{root}/")
time.sleep(0.5)
f = f"{f[:-4]}.xlsx" # ← this assumes any zipped files will be Excel files...
dfs.append(read_csv_or_excel(f))
else:
continue
appended.append(f[:-4])
pd.concat(dfs).to_excel(f"{root}.xlsx"
Lmk 如果它不起作用!我的測驗資料不是最好的我必須花更多時間制作更好的測驗資料才能 100% 有效,所以如果您有任何問題,可能只是需要進行一些小調整來修改它??
uj5u.com熱心網友回復:
您也可以嘗試在終端中僅使用 bash:
$ find . -maxdepth 5 -name *.zip | parallel unzip # this will unzip everything in one command
$ find . -maxdepth 5 -name *.xlsx | parallel # perform whatever operation you want on all the excel files
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354008.html
