创建目录Python

创建目录Python

问题描述:

我的教师提供了下面的代码,但它在从命令行运行时不能在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

/数据不存在 –

正如评论指出的@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') 

检查如果文件夹“数据”不存在。如果不存在,你必须创建它:

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