comatsupy
@comatsupy

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Python、File not found errorの対処法

下記のコードで、File not found errorが出る原因と対処法を教えていただきたいです。

path = os.path.join(os.path.dirname(file), 'dics', 'random.txt')
file = open(path, 'r', encoding = 'utf_8')

0

2Answer

Comments

  1. @comatsupy

    Questioner

    ご回答ありがとうございます。

    fileの前後にアンダーバーが2つあります。

    分かりづらい説明で申し訳ありませんが、よろしくお願いいたします。

  2. 変数fileはファイルの絶対パスまたは相対パスですよね?
    ファイルツリーは下記の様になっていますか?

    親フォルダ
     ┠ file(ファイル)
     └ dics(フォルダ)
        └random.txt(ファイル)

  3. __file__ はスクリプト自身の絶対パスです。

  4. ./dics/random.txtファイルが存在するなら、↓では?

    hoge.py
    path = os.path.join(os.path.dirname(__file__), 'dics', 'random.txt')
    file = open(path, 'r', encoding = 'utf_8')
    

    スクリプトに書く。REPLでは動作しない。

  5. @nak435
    そういうことでしたか・・・やっと質問が理解できました。

生成されたパスが変数pathに入っていますが

原因1: そのパスが想定したものでない。
対処1: 想定したパスになるように処理を変更する

原因2: そのパスは正しいが、ファイルが無い>
対処2: そのパスにファイルを作る/移動する。

1Like

Your answer might help someone💌