2016-05-12 113 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

那麼,數據/'存在? 'open'不會創建一個文件夾。 –

+0

/數據不存在 –

回答

1

正如評論指出的@Morgan Thrapp,該open()方法不會爲你創建一個文件夾。

如果該文件夾/data/已經存在,它應該工作的罰款。

否則,你就必須check if the folder exists,如果沒有,那麼create the folder.

import os 

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

所以..代碼:

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

成了這樣的事情:

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

檢查如果文件夾「數據」不存在。如果不存在,你必須創建它:

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')