Python prints error message io.UnsupportedOperation: not readable

12,132

It's happening when the file doesn't exist yet because that's when the file was opened in write mode. Write mode is not readable.

My understanding of what's happening here is when the file doesn't exist on the first call, your except block opens a file and puts one there; you then recurse for some reason, it hits the first block on this call, and completes at that level of the stack; when it returns back up to the next level, your first invocation continues, but the file reference is still in write mode, whatever the other levels of the stack have done. When it reaches the for line in file it blows up.

I would suggest you greatly simplify what you have going on here.

def export(addendum, user):
    filename = user + '.txt'
    try:
        with open(filename, 'r') as file:
            contents = file.read()
    except OSError:
        contents = ""
    day = input("What day is it (1-5)?")
    day = int(day)
    if not (1 <= day <= 5):
        print("Invalid weekday number...")
        sys.exit()
    contents += '\n' + addendum
    with open(filename, 'w') as file:
        file.write(contents)
Share:
12,132
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have searched this site for similar issues, but have not found any solutions that worked, hence, this question. I am writing a Python 3.4 program in which I have a function, export, that essentially appends data to a text file. The function checks to make sure that there is an appropriate file, if not, it creates one, and then it gets the contents of the file, adds the addendum, and overwrites the file. Python is throwing the error at for line in file: Also, upon running this program again, once the text file is already created, this error doesn't occur. Here is the function:

    def export(addendum, user):
        filename = user + '.txt'
        try:
            file = open(filename, 'r')
        except OSError:
            file = open(filename, 'w')
            export(addendum, user)
        file_contents = ''
        print('What day is it? (1-5)')
        day = input()
        day = int(day)
        if day >= 1 and day <= 5:
            for line in file:
                file_contents += line
            file = open(filename, 'w')
            new_file = file_contents + '\n' + addendum
            file.write(new_file)
            file.close()
        else:
            print('Invalid weekday number...')
            sys.exit()