3

我使用以下方法创建了一个目录:

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

createDir(OUTPUT_DIR)

现在我想创建一个用于写入的文件并将其放在我新创建的目录中,即OUTPUT_DIR. 我怎样才能做到这一点?

4

2 回答 2

6

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

import os

f = open(os.path.join(OUTPUT_DIR, 'file.txt'), 'w')
f.write('This is the new file.')
f.close()
于 2012-04-27T17:00:19.937 回答
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')
于 2012-04-27T17:01:04.717 回答