2017-03-19 16 views
0

Pythonでのテキストファイルの作成と書き込みに問題があります。私は、Python 3.5.1を実行して試してみて、作成したファイルに書き込むには、次のコードを持っています:Python:ファイルへの書き込みと書き込みエラー

from os import * 
custom_path = "MyDirectory/" 
if not path.exists(custom_path) 
    mkdir(custom_path) 
text_path = custom_path + "MyTextFile.txt" 
text_file = open(text_path, "w") 
text_file.write("my text") 

しかし、私はTypeErrorラインtext_file = open(text_path, "w")an integer is required (got type str)を言ってます。

私のコードは、ファイルの作成と書き込みの方法を示すチュートリアルのいくつかのサイトとほぼ同じなので、間違っていることはわかりません。

また、上記のコードはテキストファイルが存在しない場合は作成し、作成しない場合は作成しますか?

+1

ここに必要な返信があります。http://stackoverflow.com/a/1046674/5179092 – delca85

答えて

3

osモジュールからすべてをインポートしないでください。

from os import path, mkdir 
custom_path = "MyDirectory/" 
if not path.exists(custom_path): 
    mkdir(custom_path) 
text_path = custom_path + "MyTextFile.txt" 
text_file = open(text_path, 'w') 
text_file.write("my text") 

ネイティブファイルの「オープン」メソッドを上書きしますosモジュールで「オープン」方法もございますので。

+0

ああ、意味があります。ありがとうございました – Ryan

関連する問題