2014-04-02 113 views
-1
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

由於錯誤清楚地表明,該文件不能打開閱讀。你需要打開它進行讀/寫:

fd = open(filename, 'r+') 

,我建議你檢查出蟒蛇如何read and write files

編輯

此外,作爲Dannnno指出,您要關閉的文件,DE環內。您需要將fd.close()移出for循環。

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任何地方,但我不知道它應該是這樣,我不能幫你那裏