2014-03-25 30 views
1
def main(): 

    infileName = input("Insert To do list file: ") 
    outfileName = input("Insert the new to do list: ") 

    infile = open(infileName, "r") 
    todolist = infile.readlines() 

    outfile = open(outfileName, "w") 

    for i in range(len(todolist)): 
     print(todolist[i], file = outfile) 

     infile.close() 
     outfile.close() 
    print("New list prints to",outfileName) 

main() 

我總是收到一條錯誤消息,說print(todolist[i], file = outfile) ValueError: I/O operation on closed file.請幫助。試圖創建一個從infile到outfile的數字的列表

所有我想要做的是從被列爲

do hw
throw away trash
shower dog

和我要的是

1. do hw 
2. throw away trash 
3. shower dog 

回答

1

你有一個壓痕錯誤文件採取的待辦事項列表:

for i in range(len(todolist)): 
    print(todolist[i], file = outfile) 

    infile.close() 
    outfile.close() 

糾正這樣的:

for i in range(len(todolist)): 
    print(todolist[i], file = outfile) 

infile.close() 
outfile.close() 

如果你想在該行開始加號,你應該這樣做:

for i in range(len(todolist)): 
     outfile.write("{0}. {1}".format(str(i), todolist[i])) 
0

勞倫斯已經確定,在他的回答你的代碼的問題;你正在關閉循環內的文件,這意味着文件在你寫完第一行後關閉。但是,實際上比手動關閉文件更好。

一般情況下,當你打開一個需要安置的資源,你應該使用with塊:

with open(infileName, "r") as infile, open(outfileName, "w") as outfile: 
    todolist = infile.readlines() 

    for i in range(len(todolist)): 
     print(todolist[i], file = outfile) 

print("New list prints to",outfileName) 

這樣,一旦你在外面有塊中的文件被自動處理。

0

您正在寫封閉文件。在for循環中,您使用outfile關閉文件。關閉

您可以使用文件上下文管理器和python的枚舉函數來清理代碼。這裏是你的代碼的改版:

def main(): 

    infileName = input("Insert To do list file: ") 
    outfileName = input("Insert the new to do list: ") 

    with open(infileName, 'r') as infile, \ 
      open(outfileName, 'w') as outfile: 

     for i, line in enumerate(infile): 
      print('{}. {}'.format(i, line.rstrip()) , file=outfile) 

    print("New list prints to",outfileName) 


main() 

使用情況管理器 - 「開(...)爲INFILE」讓你忘記關閉文件Python會自動關閉它曾經上下文超出範圍。另外請注意,您可以迭代文件對象。當你這樣做,蟒蛇一次返回文件的內容一行:

for line in open('somefile.txt'): 
    print line 

另一個漂亮的技巧是枚舉。這個函數:

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.

哪個是更好地理解一個例子:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 
>>> list(enumerate(seasons)) 
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 
>>> list(enumerate(seasons, start=1)) 
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] 

最後,要注意印刷線時。 Python在讀取一行時會返回'\ n',所以當您打印從文件讀取的行時,最終會出現一個額外的,通常意外的空行。