我想讀取檔案名(A/B/C/D)并為Files檔案夾中的每個檔案呼叫方便的函式,然后處理下一個檔案(自動傳遞給下一個檔案和函式)。
我有多個檔案存盤在Files檔案夾中:
這里是目錄結構:
App/
├── main.py
└── Files/
└─B.txt
└──A.xlsx
└──folderC
| └──filec1.txt
| └──filec2.txt
└──D.xlsx
└──檔案夾F
└──fileF1.txt
└──fileF2.txt
我有多個函式存盤在main.py中:
def A_fct(fileA)。
pass。
def B_fct(fileB)。
pass。
def C_fct(fileC1,fileC2)。
pass。
def D_fct(fileD)。
pass
def F_fct(files)。
df = pd.concat([pd.read_csv(f,sep=' ',engine="python") for f in
glob.glob(files "/*.txt")],ignore_index=True)
NB:有些函式有兩個引數。
舉例:
讀取檔案名B.txt => 呼叫B_fct
讀取檔案名A.xlsx => 呼叫A_fct。等等...
我試過這個解決方案:
path = ''/span>
name_to_func = {
"A.xlsx"/span>。A_fct,
"B.txt"/span>: B_fct,
...
}
for files in os.listdir(path):
name_to_func[file_name](files)
當函式只有一個引數時,這個解決方案對我來說非常有效,但有時我遇到例外,我有一個帶有2個引數的函式,例如C_fct(fileC1,fileC2)
。我怎樣才能解決這個問題呢!
uj5u.com熱心網友回復:
你可以用os.path.isdir檢查路徑是否是一個目錄,并改變呼叫引數。
base_path = 'Files/'_span>
for name in os.listdir(base_path):
path = os.path.join(base_path, name)
if os.path.isdir(path):
files = [os.path.join(path, f) for f in os.listdir(path)]
if name_to_func[path].__code__.co_argcount == len(files)。
name_to_func[path](*files)
else:
name_to_func[path](files)
else:
name_to_func[path](路徑)
在這種情況下,檔案串列將被用作函式的引數。
。如果你不確定這個函式會得到多少個引數,你也可以重寫定義:
如果你不確定這個函式會得到多少個引數,你也可以重寫定義。
def C_fct(*files)。
files # is the list of arguments。
然而,你可以避免*符號,只需提供一個串列作為引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332345.html
標籤:
上一篇:對進入該方法的引數型別感到困惑
