LoginSignup
22
21

More than 5 years have passed since last update.

Pythonでファイルopenにちょっとつまずいた話

Posted at

はじめに

この記事はPythonでopen()関数でパス指定のトラブルシューティングの記録です。
同じようなトラブルを抱えている方への参考になれば幸いです。

結論

・raw文字列を使おう。
・フルパス、相対パスを意識しよう。

結論にいたるまで

pythonを学び始めて計算結果をテキストファイルに保存してみようってなったので
ひとまず参考書のコードをPyCharmにポチポチして実行してみる。

hoge1.py
f = open("C:\py_study\text.txt", "r", encoding="utf-8")
s = f.read()
print(s)
f.close()

#result
#OSError: [Errno 22] Invalid argument: 'C:\\py_study\text.txt'

まぁ、何かしらエラーは出ると思ってました。
そこでエラーを確認すると「\text.txt」の「\t」がタブ文字になってることに気づく。。。
解決策としてwindowsのパス指定のときraw文字列が便利って学んだことを思い出して
パス指定にraw文字列を使ってみる。

hoge2.py
f = open(r"C:\py_study\text.txt", "r", encoding="utf-8")
s = f.read()
print(s)
f.close()

#result
#aaaa
#bbbb
#cccc
#abcd

できた。

カレントディレクリにファイルを作成していればraw文字でフルパスを指定しなくてもOK
ちなみにカレントディレクトリは

import os
print(os.getcwd())

で確認できます。

カレントディレクトリが「C:\py_study」だったので

hoge3.py
f = open("text.txt", "r", encoding="utf-8")
s = f.read()
print(s)
f.close()

でもファイルの中身が確認できました。

おわり。

22
21
3

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
22
21