pythonfilereadfiledelete-filewritefile

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:

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.