LoginSignup
0
1

More than 1 year has passed since last update.

Pythonで自作モジュール(別階層)を呼び出す時

Last updated at Posted at 2023-03-25

やりたいこと

Pythonで自作モジュールを作って、呼び出す場合について。
特に、カレントではないところにモジュールフォルダがある場合にそこからの呼び出し方。

参考文献

// HTML4.0の頃から見てるけど、とほほさんはずっとWebを更新していて偉いなあ。

ソリューション

# 以下のような階層で入っているとする

(current)
 ├─ test.py       # 呼び出し元のコード 
 └─ /hapy_mod     # モジュールが入っているフォルダ
    └─ ham.py   # モジュールそのもの
ham.py
# 必要なモジュールのインポート
import pandas as pd
#-------------------------------------------------
# Excelの指定行からデータを取り出しDataFrameにして返す
# f_name:   Excelのファイル名
# s_name:   Excelのシート名
# row_num:  Excelの行番号(1オリジン)
#-------------------------------------------------
def get_df_from_excel(f_name, s_name, row_num=1):
    print(" -> get_df_from_excel: " + f_name + ", " + s_name + ", " +  str(row_num))
    work_df = pd.read_excel(f_name, sheet_name=s_name)
    # 読込み位置とindexを指定
    index = row_num - 1
    ret_df = work_df[index:]
    if (index >= 1):
        col_lists   = work_df.iloc[(index-1)]
    ret_df.columns = col_lists
    return ret_df
test.py
# 階層は . で表す
import hapy_mod.ham as hapy

in_file   = 'myリスト_0.xlsx'
in_sheet1 = 'リスト'

df1 = hapy.get_df_from_excel(in_file, in_sheet1,  4)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1