简体   繁体   中英

Simplest way to create a file and write a string to it in Python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM