I'm learning how to code in Python using TextWrangler as my text editor (using OS X), and I've been unable to open any files. Here's how I want to open the files:

file = open("genomic_dna.txt")

Whenever I try to run this, I get an error message saying it can't locate the file. Or any other file I've tried. I've also tried specifying the file path with the same result. Here's the error message I get every time:

~/Desktop/exercises/chapter_2/calculating_at_content.py:1: IOError: [Errno 2] No such file or directory: 'genomic_dna.txt'

What am I doing wrong?

  • It sounds like this is a Python problem, not TextWrangler. Or did I misunderstand your problem? – Tuesday Oct 21 '15 at 5:24

I think @timothymh is right, this is a Python question not a Textwrangler one, but regardless, to open a file with Textwrangler:

via the Finder

Just double click it. If that file type is associated with a different application then open the context menu for the file, and select "Get Info" and change the "Open with:" to Textwrangler. Click the "Change All…" if you want all files of that type to open in Textwrangler.

via the Terminal

With Textwrangler open and active, select the Textwrangler menu and "Install Command Line Tools". This will give you the edit command, so to open a text file in Documents called "My Text File.txt" you'd issue the command via the terminal of:

edit ~/Documents/My\ Text\ File.txt

and it will open in Textwrangler.

Now that's out the way…

The Python problem

You're trying to open a file without giving the full path to the file. Since you don't give a full path (either absolute or relative) the command assumes it's a relative file path, which means it will look for "genomic_dna.txt" in the current working directory.

You've also not specified a file mode, which means open will assume you want to read the file. All of which means you get an error, because that file does not exist in the current working directory.

To fix this, either:

  1. Give an absolute path, e.g. file = open("/Users/jonathan/Documents/genomic_dna.txt") (or wherever genomic_dna.txt is to be found, obviously).
  2. Give a relative path, e.g. if the current working directory is ~/PythonProjects/ then file = open("../Documents/genomic_dna.txt").
  3. If the file doesn't exist because you haven't created it yet and want to write to it, then pass the file mode, e.g. file = open("genomic_dna.txt", "w").

You might want to try using the Python interpreter to test your code out first and then transfer it to a file (by using Textwrangler to save it). To open the interpreter just type python at a terminal and press enter.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .