文件未打开进行读取

2024-05-16 16:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

def save_list(todolist, filename):
    """ writes the todo list to the filename in correct format

    save_list(todolist, filename) -> list
    """

    fd = open(filename, 'w') #creates file
    for line in fd:
        date = as_date_string(line[0]) #to put into correct format
        chore = line[1] # assigns chore from touple value
        fd.writelines(text)
        fd.close()
    print result

当我试图运行这个函数时,我得到了错误

^{pr2}$

该函数应该加载一个列表并将该列表写入一个文件 例如 save_list(load_list('todo.txt'), 'todo.txt') 应该用相同的信息重写文件


Tags: theto函数informatdatesaveline
2条回答

正如错误清楚地说明的那样,文件没有打开以供读取。您需要打开它进行读/写:

fd = open(filename, 'r+')

我建议您查看如何在python中read and write files。在

编辑

而且,正如Dannnno指出的,您正在de loop中关闭文件。您需要将fd.close()移出for循环。在

看看你的代码。在for循环中关闭文件。你也有它只写,你想读/写

fd = open(filename, 'r+') #creates file
for line in fd:
    date = as_date_string(line[0]) #to put into correct format
    chore = line[1] # assigns chore from touple value
    fd.writelines(text)
fd.close()

你也没有在任何地方定义text,但我不知道它应该是什么,所以我不能帮助你

相关问题 更多 >