Alex
Alex

Reputation: 61

NoneType error when opening file

So I've been trying to figure out why it's giving me this error. If I put this:

def open_file():
    fp = open("ABC.txt")
    return fp

file = open_file()

count = 1

for line in file:
    if count == 9:
        line9 = line
    if count == 43:
        line43 = line
#blahblahblah more programming

This works, but this gives me NoneType object is not iterable:

def open_file():
    while True:
        file = input("Enter a file name: ")
        try:
            open(file)
            break
        except FileNotFoundError:
            print("Error. Please try again.")
            print()

file = open_file()

count = 1

for line in file:  #here is where I get the error
    if count == 9:
        line9 = line
    if count == 43:
        line43 = line

I think it's just some silly mistake but I can't seem to find it. Thanks for your time!

Upvotes: 0

Views: 1140

Answers (1)

Curtis Lusmore
Curtis Lusmore

Reputation: 1872

Your open_file function has no return statement, so it returns None. You should try something like

def open_file():
    while True:
        file = input("Enter a file name: ")
        try:
            return open(file)
        except FileNotFoundError:
            print("Error. Please try again.")
            print()

Upvotes: 3

Related Questions