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?
Best Answer
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: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:
file = open("/Users/jonathan/Documents/genomic_dna.txt")
(or wherever genomic_dna.txt is to be found, obviously).~/PythonProjects/
thenfile = open("../Documents/genomic_dna.txt")
.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.