文件未打开以供阅读

时间:2014-04-02 02:30:52

标签: python file rewrite

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

当我尝试运行此功能时,我收到错误

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    save_list(load_list('todo.txt'), 'todo.txt')
  File "C:\Users\Sam\Desktop\CSSE1001\Assignment\assign1.py", line 58, in save_list
    for line in fd:
IOError: File not open for reading

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

2 个答案:

答案 0 :(得分:2)

由于错误清楚地说明,该文件未打开以供阅读。你需要打开它进行读/写:

fd = open(filename, 'r+')

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

修改

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

答案 1 :(得分:0)

看看你的代码。您在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,但我不知道它应该是什么,所以我无法帮助你