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()
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()
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.
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().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()