How to write a file and then delete it

68 Views Asked by At

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

3

There are 3 best solutions below

3
Antoine On BEST ANSWER

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.

0
SIGHUP On

The issue here is that Windows won't let you delete a file (or mark ready for deletion) if it's open in some process. Unix type systems will allow you to do this.

Here are two pieces of code. The first one will work on (for example) macOS. The second will work on Windows and is therefore a cross-platform compatible variant.

import os

F = 'foo.txt'

with open(F, 'x') as foo:
    foo.write('I am Foo')

with open(F) as foo:
    print(foo.read())
    os.remove(F)

import os

F = 'foo.txt'

with open(F, 'x') as foo:
    foo.write('I am Foo')

with open(F) as foo:
    print(foo.read())

os.remove(F)
0
AFRobertson On

An alternative is to use tempfile from the standard library:

from tempfile import TemporaryFile

with TemporaryFile() as f:
    f.write("XYZ")
    f.seek(0)
    str_read_file = f.read()

This context manager closes and deletes the temporary file after the context.