0

Is there any simpler way for writing a string to a file than this:

f = open("test.txt", "w+")
f.write("test")
f.close()

I wish the return value of write was not None so that I could do this:

open("test.txt", "w+").write("test").close()
1
  • 8
    fewer lines != better code Commented May 2, 2012 at 20:32

2 Answers 2

11
with open("test.txt", "w") as f_out:
    f_out.write(your_string)

When you use with open, you don't need to do f_out.close(); this is done for you automatically.

Sign up to request clarification or add additional context in comments.

1 Comment

with open('test.txt', 'w') as f: f.write('text') if you must have a one-liner. And it's four characters shorter than your desired open("test.txt", "w+").write("test").close().
1

You can do chaining if you want, but you will have to write your own wrapper, useless but fun exercise

class MyFile(file):
    def __init__(self, *args, **kwargs):
        super(MyFile, self).__init__(*args, **kwargs)

    def write(self, data):
        super(MyFile, self).write(data)
        return self


MyFile("/tmp/tmp.txt","w").write('xxx').close()

Comments

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.