Python 打印错误消息 io.UnsupportedOperation:不可读

Python prints error message io.UnsupportedOperation: not readable

我已经在该网站上搜索过类似问题,但没有找到任何有效的解决方案,因此提出了这个问题。 我正在编写一个 Python 3.4 程序,其中有一个函数 export,它本质上是将数据附加到文本文件。 该函数检查以确保有合适的文件,如果没有,它会创建一个,然后它获取文件的内容,添加附录,并覆盖文件。 Python 在 for line in file: 处抛出错误 此外,再次 运行 此程序时,一旦创建了文本文件,就不会发生此错误。 这是函数:

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()

当文件尚不存在时会发生这种情况,因为那时文件是以写模式打开的。写模式不可读。

我对这里发生的事情的理解是,当文件在第一次调用时不存在时,您的 except 块会打开一个文件并将一个文件放在那里;然后你出于某种原因递归,它命中这个调用的第一个块,并在堆栈的那个级别完成;当它 returns 返回到下一层时,您的第一次调用将继续,但文件引用仍处于写入模式,无论堆栈的其他层已经完成。当它到达 for line in file 时它爆炸了。

我建议您大大简化您在这里进行的操作。

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)