2014-03-25 88 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',所以当您打印从文件读取的行时,最终会出现一个额外的,通常意外的空行。