errolflynn
errolflynn

Reputation: 641

Python: Having trouble reading in a file when prompted

I am having issues reading in a file. I prompt the user to load a file and then use the input as an argument in a function which simply attempts to load the given filename and print each line. I am receiving an IOError: No such file or directory: 'filename.txt'

filename = raw_input("Filename to load: ")
print load_records(students, filename)

def load_records(students, filename):
    #loads student records from a file
    records = []
    in_file = open(filename, "r")
    for line in in_file:
        print line

I suspect that I am not accessing the correct directory.

Upvotes: 0

Views: 68

Answers (1)

jpmc26
jpmc26

Reputation: 29866

Given the error, I will conclude that you typed nothing but filename.txt when prompted. This will cause Python to search for a file named filename.txt in the current directory. So if your command prompt's current directory is C:\dev, this is equivalent to C:\dev\filename.txt (the absolute path). You should either change the current directory to the directory containing filename.txt or specific the absolute path when prompted. The latter would probably be simpler as it wouldn't be as likely to mess up Python's ability to find your other modules.

Upvotes: 2

Related Questions