Writing to a new directory in Python without changing directory

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

    This will create the file feed/address/file.txt in the same directory as the current script:

    import os
    
    file_name = 'file.txt'
    script_dir = os.path.dirname(os.path.abspath(__file__))
    dest_dir = os.path.join(script_dir, 'feed', 'address')
    try:
        os.makedirs(dest_dir)
    except OSError:
        pass # already exists
    path = os.path.join(dest_dir, file_name)
    with open(path, 'wb') as stream:
        stream.write('foo\n')
    

提交回复
热议问题