Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a file and then delete it

I am a C# programmer and need to go for python now. It is my 2nd day so far.
I need to write a file, read it and then delete it.
In C# that’s easy peasy.

string strPath = @"C:\temp\test.txt";
using (StreamWriter writer = new StreamWriter(strPath))
{ writer.WriteLine("XYZ");}

string readText = File.ReadAllText(strPath);

File.Delete(strPath);

the stream is closed by the using

In python I came up to this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open(strPath, "xt") as f:
    f.write("XYZ")
f.close()

f = open(strPath, "r")
strReadFile = f.read()

os.remove(strPath)

but try as I might I still get the error telling me that the file is in usage.
I therefore googled: "Python write read and delete a file" but nothing came up

Thanks
Patrick

>Solution :

With your second exemple, you need to manualy close the file and on the first the with context handler does it for you.

with open(strPath, "xt") as f:
    f.write("XYZ")

f = open(strPath, "r")
strReadFile = f.read()
f.close()

os.remove(strPath)

Both ways are valid.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading