1

Python 3.2.3のopen()関数に問題があります。次のコードは、2.7.3を使用するとうまく機能しますが、Python3では機能しません。

    file = open("text.txt", 'r')

Python3では、標準のIOErrorが発生します。

    IOError: [Errno 2] No such file or directory: 'text.txt'

参照されるtext.txtファイルは、pythonファイルと同じディレクトリにあることに注意してください。

何か案は?

4

3 に答える 3

3

ファイル名は、ファイルのディレクトリに対して相対的ではなく、現在の作業ディレクトリ(で確認できますos.getcwd()) に対して相対的です。

Python ファイルに相対的な名前のファイルを開きたい場合は、次の__file__ようにマジック変数を使用できます。

import os.path
fn = os.path.join(os.path.dirname(__file__), 'text.txt')
with open(fn, 'r') as file:
   # Do something, like ...
   print(file.read())
于 2012-04-18T17:06:49.473 に答える
0

私は Pydev で Eclipse を使用していましたが、プロジェクト レベルではなくパッケージ内に text.txt ファイルがありました。パッケージ内のファイルにアクセスするには、次を使用する必要があります。

 file = open("[package]/text.txt", 'r')
于 2012-04-19T00:53:59.547 に答える
0

You are trying to open a file in read mode, and this file has to exist.

Perhaps problem is that the file just doesn't exist in your python3 path and therefore the open command fails, but 'text.txt' exist on your python2.7 lib (or somewhere in python2.7 path) and this is why python is able to locate the file and open it.

You can just try this code (this will assure you the file exist since you create it):

f = open('text.txt','w')
f.close()
f.open('text.txt','r')
于 2012-04-18T17:19:14.247 に答える