Use safe way through "with" statement to work with files

It's unsafe to just open and write to file. Cause if something went wrong
during writing to file we won't close fd.

Change-Id: I924b8962b3e0c936f3a20260844178783feaf544