Writing Text Files with Python

This is a super-basic guide intended to be comprehensible by pretty much anyone who has access to a Mac. We’re going to use Python to create a simple text file in ~5 minutes using these steps:

  1. Open a terminal

  2. Create a directory (easy)

  3. Launch a python terminal from within the new directory

  4. Create a file called test.txt inside the new directory

  5. Verify that the file was created


1. Open a terminal

  • Go to Applications => Utilities => Terminal

Note: I highly suggest you use a shortcut key helper app like Alfred or Quicksilver - it is so much better than anything built into MacOS, and is a huge time-saver in the long run.


2. Create a directory

For this example, we’ll create a directory on the Desktop named… python_write_files.

cd ~/Desktop
mkdir python_write_files
cd python_write_files

3. Launch Python

As simple as typing… python.

python

What this ☝does (typing python) — Your bash terminal window that you have been typing bash commands into will now act as a python interpreter. So you’ll see each new line preceded by >>>. See below…


4. Create a file called test.txt

Remember: since we launched the python interpeter from our directory python_write_files the text file will be created inside that directory.

The next 3 lines of code are in fact very simple python.

f = open("test.txt", "w")
f.write("Hey there from Python")
f.close()

5. Verify that the file was created

First, we’ll need to exit out of the python interpreter. Just type exit().

exit()

Then, back in the terminal, we’ll ls the directory - ls just lists the contents of the directory we’re in.

ls
test.txt
open test.txt

Typing the command open test.txt will launch your system’s default application for reading text files. In my case, it’s TextEdit.

hey-there-from-python.png