How do I write and read plain text files in Python?

Writing and reading plain text files is easy in Python. Look at the following functions.

def write_file(txt, filename):
    with open(filename, ‘w’) as f:
        f.write(txt)

def read_file(filename):
    with open(filename, ‘r’) as f:
        return f.read()

def test_text_io():
    txt = ‘text’
    write_file(txt, ‘spam.txt’)
    s = read_file(‘spam.txt’)
    print s

IF you define the functions and then call test_text_io(), it should create a file called ‘spam.txt’ in your current working directory and print ‘text’ in your console.

Comment