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.

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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