For my script, I am trying to open a text file and print out the information in the console window. However, I am having trouble finding the right way to load it.

To start, I need to figure out how to load something in the same directory as the script, so far I have this:

listnum = input("> ")
fn = 'VocabList.'+str(listnum)+'.txt'
wordfile=open(fn,"r")

This returns

wordfile=open(fn,"r")
IOError: [Errno 2] No such file or directory: 'VocabList.0.txt'

So, what am I doing wrong?
Also, is it possible to load a file in another directory?

Thanks in advance.

First of all, what version of Python are you using? If it's anything earlier than 3.0 do not use input() , rather raw_input() (in the same manner). It already forces the user input to string and doesn't allow for malicious things to happen.

Now, the problem in this case is likely that you don't have the text file in the same directory as the script's working directory. There's a few ways to go about this.

1: change the current working directory with os.chdir() , and then open the file.

2: Use the absolute path to the file (meaning if the file is located under the directories \usr\foo\bar use fh = open('\usr\foo\bar\my_file.txt') EDIT:
To make this easier you can use os.path.join like so:

import os

my_file_path = '\usr\foo\bar'
listnum = raw_input("> ")
fn = 'VocabList.'+listnum+'.txt'
wordfile=open(os.path.join(my_file_path, fn), "r")

there are ways to find the directory of the script, but if you are in the directory already and start the script then "open" should automatically look there anyway. Are you sure that's the name of the file and the upper and lower case match? Or if you're on windows you might have accidentally named the file "VocabList.0.txt.txt" because it hides extensions by default.

Thanks jlm you solved my problem. I had originally tried using an absolute path, but Python does not like Linux shortcuts. So, this was all caused because I typed out ~/myscript.py instead of /home/blah/myscript.py....laziness fails!

Thank you for your reply though. Learned something new with that os.chdir function!

Tkinter's FileDialog is a easy way to select a file name. Double click to select a directory or file.

from Tkinter import *
from FileDialog import FileDialog

def GetFilename( dir = "" ):
    top = Tk()

    d = FileDialog( top )
    fname = d.go( dir )
    if fname == None :
        print "No file found", fname
        fname = "****"
    else :
        print "The file is %s" % (fname)

    return fname

##================================================================
if __name__ == '__main__':
    ret_filename = GetFilename( "/home/")
    print "filename returned is %s" % (ret_filename)
This question has already been answered. Start a new discussion instead.