I'm writing to file and closing it. Next moving/renaming it f_new -> f_old. Then opening f_old and trying to read it, but it seems empty. But the file is moved and has the proper content. What am I missing? (python 3.11.2 on debian 12.8)
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
The above results in
1: hello
2:
while I expected:
1: hello
2: hello
I tried os.replace
, os.rename
and shutil.move
all with same results.
Thank you for a help :)
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.