文件未正确关闭

File is not closing properly

我不确定为什么,但是文件 'refined.txt' 没有正确关闭(见下面的代码)。当我尝试在最后一行代码中重命名文件时,出现 Windows 错误 ("The process cannot access the file because it is being used by another process")。

重命名此文件很重要,因为这段代码是 for 循环的一部分,所以如果我不将文件重命名为唯一的名称,它将被覆盖。

我希望有人能告诉我为什么文件没有正确关闭。

代码:

    of = open('refined.txt')
    d=of.readlines()

    for line in d[:20]:
        #some code

    of.close()    
    os.rename('refined.txt', new)

尝试使用 with 语句打开文件,看看是否有任何不同。

with open('refined.txt') as of:
    d = of.readlines()

for line in d[:20]:
    #some code

os.rename('refined.txt', new)