---
# System prepended metadata

title: 切割block

---

# 切割block

## 環境需要套件：
```typescript=
pip install pandas
pip install openpyxl
```

## 切割檔案執行指令：
```typescript=
python .\split.py '.\test\meta.xlsx' '.\test' '.\test\output'
```

.\split.py：執行的py檔

.\test\meta.xlsx：辨識檔的路徑及檔名
meta.xlsx(辨識檔)：辨識檔式是讓程式知道哪個輸入檔的哪個Block要輸出成什麼檔名。檔案的第一行第一列必須填Block，每個輸入檔裡不要切割的Block用Blank或是-填滿(下圖為例)。檔名不一定要meta.xlsx，但副檔名一定要是.xlsx。第一列為要切割的檔案名，必須加上副檔名，可以處理.xlsx和.gpr。第一欄為哪一個block。表格裡面的欄位會是最後輸出的檔案名
![](https://i.imgur.com/EETidru.png)

.\test：放要被切割的檔案(.gpr和.xlsx)的資料夾路徑，也就是輸入檔(.gpr或.xlsx)必須是放在這個路徑底下

.\test\output：輸出的路徑，最後輸出的.xlsx會放在這個路徑底下

## 資料夾結構
![](https://i.imgur.com/qHdPPaN.png)



## split.py程式碼：
```typescript=
import pandas as pd
import sys
import os

meta_path = sys.argv[1]
dir_path = sys.argv[2]
output_path = sys.argv[3]

try:
    meta = pd.read_excel(meta_path, index_col=0, engine='openpyxl')
except:
    meta = pd.read_excel(meta_path, index_col=0)


for file_name in meta.columns:
    if '.gpr' in file_name:
        with open (os.path.join(dir_path, file_name), mode="r") as file:
            while True:
                content = file.readline()
                if ('Block' in content) and ('ID' in content) and ('Row' in content) and ('Column' in content):
                    data=file.readlines()
                    break
                    
        columns = content.replace('"','').strip('\n').split("\t")
        data = [v.replace('"','').strip("\n").split("\t") for v in data]
        df = pd.DataFrame(data, columns = columns)

    elif '.xlsx' in file_name:
        try:
            df = pd.read_excel(os.path.join(dir_path, file_name), engine='openpyxl')
        except:
            df = pd.read_excel(os.path.join(dir_path, file_name))
        if ('Block' and 'Column' and 'Row' and 'ID') not in df.columns:
            for i in range(len(df)):
                df_columns = list(df.iloc[i, :])
                if ('Block' and 'Column' and 'Row' and 'ID') in df_columns:
                    break

            df = df.iloc[i+1:, :]
            df.columns = df_columns
            df = df.reset_index(drop=True)

    df.Block = df.Block.apply(str)

    for block in meta.index:
        label = meta.loc[block, file_name]
        if(label != '-' and label != 'Blank'):
            print(label)     
            split_block = df[df['Block'] == str(block)]
            split_block.to_excel(os.path.join(output_path, (str(label) + '.xlsx')), index=False)
```