用with方法打开

这种方法打开的好处就是可以不用执行file.close()方法,就可以自动关闭文件,而且可以同时打开多个文件(应该是在2.7以后的版本)

with open("hello.txt") as f,open("world.txt") as f1:
    for line in f:
        print line,

 

open和file的区别

When opening a file, it’s preferable to use open() instead of invoking the file constructor directly.

这是官网的解释,推荐用open打开文件,而不是用file直接调用。open更像是一个代理,在3.0中可以下面调用的不叫file了,所以如果为了以后的兼容性还是用open的好,这样不管下面调用的是file还是其它,都不会影响文件的操作

 

posted on 2016-01-01 22:23  牧羊伯爵  阅读(142)  评论(0编辑  收藏  举报