PythonでファイルをOpenする時にそのファイルのpathを指定して
下のコードのようにファイルを開く時がある。
demo.py
with file.open("rb") as f:
この時に、ファイルのパスを格納しているfileはstr型ではなく、
WindowsPath型でないと
"'str' object has no attribute 'open'"
というエラーが生じる。
その場合はstr型をWindowsPath()を用いてWindowsPath型にしないといけない。
下にサンプルコードを載せる
sample.py
import os
#パスをstr型で指定する
#このfileで指定のファイルを開くとエラー
path = os.getcwd()
file = os.path.join(path,'GV2.xlsx')
print(type(file))
#str型のpathをWindowsPath型にする
file_dir = WindowsPath(file)
print(type(file_dir))
#ファイルを開く
with file_dir.open("rb") as f: