Python文件无法正确关闭

时间:2018-08-20 18:47:04

标签: python python-3.x

我的文件未正确关闭,我无法弄清原因:

open_sample_file = codecs.open(ssis_txt_files_2[a], 'r', "utf-16")


whatever = open_sample_file.readlines()

open_sample_file.close
print(open_sample_file)

输出:

<codecs.StreamReaderWriter object at 0x0331F3B0>

输出不应该返回None吗?

2 个答案:

答案 0 :(得分:2)

您必须致电     open_sample_file.close()

答案 1 :(得分:1)

其中之一,您需要调用close方法:

open_sample_file.close()

然后,将得到一个关闭的文件,而不是None

>>> open_sample_file
<closed file 'filename', mode 'r' at 0x109a965d0>

最后,在Python中处理文件的常用方法是使用with-statements,它会为您关闭文件:

with codecs.open(filename) as open_sample_file:
    # do work
# the file will be closed automatically when the block is done