LoginSignup
0
0

More than 5 years have passed since last update.

Python Open fileする時の注意点

Posted at

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:
0
0
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
0