tags:

views:

64

answers:

4

I saved a file as DictionaryE.txt in a Modules folder I created within Python. Then I type:

fh = open("DictionaryE.txt")

I get this error message:

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    fh = open("DictionaryE.txt")
IOError: [Errno 2] No such file or directory: 'DictionaryE.txt'

What am I doing wrong? Could someone please describe a specific, detailed step-by-step instruction on what to do? Thanks.

+1  A: 

Use the full path to the file? You are trying to open the file in the current working directory.

Laurion Burchall
And how do I figure out the full path to the file?
Justin Meltzer
The answer below that suggests using the path to the current file is probably a good way.
Laurion Burchall
A: 

probably something like:

import os
dict_file = open(os.path.join(os.path.dirname(__file__), 'Modules', 'DictionaryE.txt'))

It's hard to know without knowing your project structure and the context of your code. Fwiw, when you just "open" a file, it will be looking in whatever directory you're running the python program in, and __file__is the full path to ... the python file.

jeremiahd
+3  A: 

As other answers suggested, you need to specify the file's path, not just the name.

For example, if you know the file is in C:\Blah\Modules, use

fh = open('c:/Blah/Modules/DictionaryE.txt')

Note that I've turned the slashes "the right way up" (Unix-style;-) rather than "the Windows way". That's optional, but Python (and actually the underlying C runtime library) are perfectly happy with it, and it saves you trouble on many occasions (since \, in Python string literals just as in C ones, is an "escape marker", once in a while, if you use it, the string value you've actually entered is not the one you think -- with '/' instead, zero problems).

Alex Martelli
+1 I didn't know this. All the while I was using `r"C:\path\to\file.txt"`
Kit
Yes!!!! This worked! thanks!
Justin Meltzer
+1 The right way indeed. Like `:` for path separators. :)
Matt Joiner
A: 

To complement Alex's answer, you can be more specific and explicit with what you want to do with DictionaryE.txt. The basics:

READ (this is default):

fh = open("C:/path/to/DictionaryE.txt", "r")

WRITE:

fh = open("C:/path/to/DictionaryE.txt", "w")

APPEND:

fh = open("C:/path/to/DictionaryE.txt", "a")

More info can be found here: Built-in Functions - open()

Kit