Python文件未正确关闭

2024-10-04 11:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我的文件未正确关闭,我无法找出原因:

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吗?你知道吗


Tags: 文件sampletxtclose原因filesopenutf
2条回答

你得打电话 open_sample_file.close()

首先,需要调用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

相关问题 更多 >