2012-04-27 57 views
1

创建一个目录中的文件我创建使用目录:在我的工作目录

def createDir(dir_name): 
    try:  
     os.mkdir(dir_name) 
     return True; 
    except: 
     return False 

createDir(OUTPUT_DIR) 

现在我想创建一个用于写入的文件,并放在我的新创建的目录中,也就是里面OUTPUT_DIR。我怎样才能做到这一点?

回答

4

使用python内置函数open()来创建一个文件对象。

import os 

f = open(os.path.join(OUTPUT_DIR, 'file.txt'), 'w') 
f.write('This is the new file.') 
f.close() 
+3

这是更好地使用'os.path.join'比'+ '/' +'。 – Chris 2012-04-27 17:03:35

+0

谢谢...答案已经更新。 – garnertb 2012-04-27 17:05:45

3
new_file_path = os.path.join(OUTPUT_DIR, 'mynewfile.txt') 

with open(new_file_path, 'w') as new_file: 
    new_file.write('Something more interesting than this') 
+0

Python> = 2.7 only – 2012-04-27 17:02:07

+0

为什么> = 2.7? 2.5中引入了'with'(参见[docs](http://docs.python.org/reference/compound_stmts.html#the-with-statement))。 – Chris 2012-04-27 17:03:01

+0

真的吗?我的错。 – 2012-04-27 17:04:16