2

I have this block of code that reliably creates a string object. I need to write that object to a file. I can print the contents of 'data' but I can't figure out how to write it to a file as output. Also why does "with open" automatically close a_string?

with open (template_file, "r") as a_string:
   data=a_string.read().replace('{SERVER_NAME}', server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}', content_path).replace('{DAMPATH}', dampath).replace('{ENV}', env).replace('{CACHE_DOCROOT}', cache_docroot)
3
  • a_string.write(your_string_object) should work inside the with block Commented Dec 1, 2015 at 15:36
  • Do you want to write the string to the file or do you want to read the file and replace parts of the read string? Commented Dec 1, 2015 at 15:37
  • I need to read the template file into memory, make changes to it then write out the (changed) object to a new file. I do not want to edit the file "in place." Commented Dec 1, 2015 at 15:55

2 Answers 2

3

I can print the contents of 'data' but I can't figure out how to write it to a file as output

Use with open with mode 'w' and write instead of read:

with open(template_file, "w") as a_file:
   a_file.write(data)

Also why does "with open" automatically close a_string?

open returns a File object, which implemented both __enter__ and __exit__ methods. When you enter the with block the __enter__ method is called (which opens the file) and when the with block is exited the __exit__ method is called (which closes the file).

You can implement the same behavior yourself:

class MyClass:
    def __enter__(self):
        print 'enter'
        return self

    def __exit__(self, type, value, traceback):
        print 'exit'

    def a(self):
        print 'a'

with MyClass() as my_class_obj:
     my_class_obj.a()

The output of the above code will be:

'enter'
'a'
'exit'
Sign up to request clarification or add additional context in comments.

Comments

0
with open (template_file, "r") as a_string:
   data=a_string.read().replace('{SERVER_NAME}', server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}', content_path).replace('{DAMPATH}', dampath).replace('{ENV}', env).replace('{CACHE_DOCROOT}', cache_docroot).replace('{SLD}', sld)

filename = "{NNN}_{BRAND}_farm.any".format(BRAND=brand, NNN=nnn)
with open(filename, "w") as outstream:
    outstream.write(data)

1 Comment

I learned chaining yesterday and string formatting today. I don't know if I should be closing the file but Imet my goal to be able to generate a config file and name it in one fell swoop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.