79322507

Date: 2025-01-01 23:44:36
Score: 1
Natty:
Report link

Like the @Blckknght say, the "close" is a method, not a property, so, you missed the parentheses "()" when call "close".

But, we have some better way to do this task, with automatic close file when is not more necessary.

The fixed script python that you show to us:

import shutil
import os

f_new = "file.new"
f_old = "file.old"
content = "hello"

fn = open(f_new, "w")
fn.write(content)
fn.close()

print("1:", content)

#os.replace(f_new, f_old)
shutil.move(f_new, f_old)

fo = open(f_old, "r")
cont_old = fo.read()
print("2:", cont_old)
fo.close()

And here, are the improved script that make the same task:

import shutil
import os

new_file = "new_file.txt"
old_file = "old_file.txt"

content = "hello"

with open(new_file, "w") as file:
    file.write(content)

print("1:", content)

#os.replace(f_new, f_old)

shutil.move(new_file, old_file)

with open(old_file, "r") as file:
    old_content = file.read()
    
    print("2:", old_content)

You can see more about the keyword "with" on this documentation.

Basically, the "with" is an automatic clean-up that can be defined in which helps to clean up some "trash" or "manual" data/variable.

Reasons:
  • Blacklisted phrase (1): this document
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Blckknght
  • Low reputation (0.5):
Posted by: Ramon