Writing to a new directory in Python without changing directory

前端 未结 3 2123
被撕碎了的回忆
被撕碎了的回忆 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

    First, I'm not 100% confident I understand the question, so let me state my assumption: 1) You want to write to a file in a directory that doesn't exist yet. 2) The path is relative (to the current directory). 3) You don't want to change the current directory.

    So, given that: Check out these two functions: os.makedirs and os.path.join. Since you want to specify a relative path (with respect to the current directory) you don't want to add the initial "/".

    dir_path = os.path.join(self.feed, self.address)  # will return 'feed/address'
    os.makedirs(dir_path)                             # create directory [current_path]/feed/address
    output = open(os.path.join(dir_path, file_name), 'wb')
    

提交回复
热议问题