Writing to a new directory in Python without changing directory

前端 未结 3 2138
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 09:50

Currently, I have the following code...

file_name = content.split(\'=\')[1].replace(\'\"\', \'\') #file, gotten previously
fileName = \"/\" + self.feed + \"/\" +         


        
3条回答
  •  一整个雨季
    2021-02-08 09:56

    Commands like os.mkdir don't actually require that you make the folder in your current directory; you can put a relative or absolute path.

    os.mkdir('../new_dir')
    os.mkdir('/home/you/Desktop/stuff')
    

    I don't know of a way to both recursively create the folders and open the file besides writing such a function yourself - here's approximately the code in-line. os.makedirs will get you most of the way there; using the same mysterious self object you haven't shown us:

    dir = "/" + self.feed + "/" + self.address + "/"
    os.makedirs(dir)
    output = open(os.path.join(dir, file_name), 'wb')
    

提交回复
热议问题