I have not used the with statement, but am somewhat familiar with its purpose. With the follow code, the #1 block works as expected, but #2 -- which, correct me here, should do the same thing as the first one -- throws the following exception FileExistsError: [Errno 17] File exists: 'mydir'.
import os
if not(os.path.exists('mydir')):
    os.makedirs('mydir')
path = 'mydir'
filename = 'msg.txt'
filename2 = 'msg2.txt'
#1
with open(os.path.join(path, filename), 'w') as temp_file:
    temp_file.write("hello")
#2
temp_file = open(os.path.join(path, filename2), 'w')
temp_file.write("hello again")
temp_file.close()   
 
     
     
    