2016-05-12 8 views
0

講師は次のコードを提供しましたが、コマンドラインから実行するとOS Xで動作しません。ディレクトリを作成するPython

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt' 
fout = open(file_name, 'w') 

エラーメッセージ:

Traceback (most recent call last): 
    File "write_a_poem_to_file.py", line 12, in <module> 
    fout = open(file_name, 'w') 
IOError: [Errno 2] No such file or directory: 'data/poem1.txt' 

私はクラスに着く前からのPythonを書いていると、少し研究を行った、それはあなたがディレクトリを作成するために、osモジュールをインポートする必要があると思います。

次に、そのディレクトリにファイルを作成するように指定できます。

ファイルにアクセスする前に、そのディレクトリに切り替える必要があると思います。

私は間違っているかもしれませんが、私は別の問題がないかと思います。

+0

'data /'は存在しますか? 'open'はフォルダを作成しません。 –

+0

/データが存在しません –

答えて

1

@Morgan Thrappのコメントに記載されているように、open()メソッドはフォルダを作成しません。

フォルダ/data/が既に存在する場合は正常に動作するはずです。

そうでない場合は、あなたが、その後、create the folder.

import os 

if not os.path.exists(directory): 
    os.makedirs(directory) 

..だからあなたのコードをcheck if the folder existsに持って、そうでない場合はされます:

import os 

folder = 'data/' 

if not os.path.exists(folder): 
    os.makedirs(folder) 

filename = raw_input('Enter the name of your file: ') 

file_path = folder + filename + '.txt' 

fout = open(file_path, 'w') 
0

チェック:

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt' 
fout = open(file_name, 'w') 

はこのようなものになりましたフォルダ "データ"が存在しない場合存在しない場合は、作成する必要があります。

import os 

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt' 
if not os.path.exists('data'): 
    os.makedirs('data') 
fout = open(file_name, 'w') 
関連する問題