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

Mic*_*l A 1 python

我创建了一个目录:

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

createDir(OUTPUT_DIR)
Run Code Online (Sandbox Code Playgroud)

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

gar*_*rtb 5

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

import os

f = open(os.path.join(OUTPUT_DIR, 'file.txt'), 'w')
f.write('This is the new file.')
f.close()
Run Code Online (Sandbox Code Playgroud)

  • 最好使用`os.path.join`而不是`+'/'+`. (3认同)