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:

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

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s