path = './file.txt'
os.remove(path)
import os

os.remove(path) is equal to os.unlink(path), so how can I delete the file if it just becomes unlinked?

Also I haven't tried to yet, but does './file.txt' work as is or do I must provide the full path?
Or do I just need to use the 'file.txt' if it the same folder? Or they both work the same like os.remove(path) and os.unlink(path)?

And if './file.txt' works then what about '../file.txt'?

Dani AI

Generated

Short, practical summary and next steps (building on and )

Removing a filename (what os.remove / os.unlink do) only removes the directory entry — it makes the filesystem treat the blocks as reusable but does not reliably erase the raw bytes immediately (and if a process still has the file open the space isn’t reclaimed until the handle closes). (man7.org)

Opening a file in write/truncate mode clears its visible contents (file size goes to zero) but that operation does not guarantee physical overwrites of all previously-stored sectors, and modern filesystems (journaling or copy-on-write) and backups/snapshots can leave extra copies. Tools that “overwrite” a file (shred/srm) warn they are unreliable on many modern filesystems and on SSDs. (man7.org)

If the goal is just to free space: a normal unlink is fine. If the goal is to make data unrecoverable, follow platform-appropriate methods:

  • On HDDs and simple filesystems: authenticated shredders can help — but read their caveats first. (gnu.org)
  • On Windows: use a vetted tool such as SDelete for secure overwrite of files or free space. (learn.microsoft.com)
  • On SSDs/NVMe: use the drive’s firmware sanitize/secure-erase or a vendor tool (or rely on full-disk encryption + secure key destruction); simple overwrites are not reliable because of wear-leveling and overprovisioning. See NIST guidance on sanitization for recommended approaches. (tinyapps.org)

If you want to try an application-level overwrite in Python before permanently deleting (note: this is only sometimes effective), overwrite the file contents with random bytes, flush and fsync, then delete or send to the trash. Example pattern (opens in update/binary mode, writes random data, forces disk sync):

import os

def overwrite_random(path, passes=1, chunk=65536):
    size = os.path.getsize(path)
    with open(path, "r+b") as f:
        for _ in range(passes):
            f.seek(0)
            rem = size
            while rem:
                n = min(chunk, rem)
                f.write(os.urandom(n))
                rem -= n
            f.flush()
            os.fsync(f.fileno())

To move items to the OS Recycle/Trash (instead of immediate unlink), use a platform-aware helper (for example the send2trash package in Python or shell APIs such as SHFileOperation on Windows). (pythonrepo.com)

Cautions: for sensitive data prefer firmware-level sanitize or full-disk encryption + crypto-erase; for disposal of media follow NIST SP 800-88 recommendations. ()

Recommended Answers

All 7 Replies

how can I delete the file if it just becomes unlinked?

When you say "delete", what exactly do you mean? Scrambling the file? Because when most people say "delete", they mean "removing the file system entry", which is exactly what remove/unlink does.

Also I haven't tried to yet, but does './file.txt' work as is or do I must provide the full path?

You can use relative as well as absolute file names. So all of 'file.txt', './file.txt', '../file.txt' and '/path/to/file.txt' will work.

By delete I mean free up the physical space.

Although now you bring something else to my attention because I know about data recovery so if I rewrite the file and then delete it will that be the most secure deletion?

with open(path, 'w'):
    os.remove(path)

And will this work for any type of file? Like say an executable, or will it only work for text files?

I don't wanna unlink it but have still have it lingerieng around cluttering up my hard memory.

open(path,"w").write("")
os.remove(path)

Will that zero out the bits and bytes?

If there's no file system entry for a file, it does not consume space. Zeroing the bytes of a file will not make it consume less space, but it will make it harder to recover the file after you delete it. However writing the empty string to a file before deleting it will not zero the bytes. It will do basically nothing (it's pretty much the same as deleting the original file, creating a new empty one and then deleting that as well).

If all you want is to free disk space, just delete the file with unlink/remove.

But open(path, "w")? The "w" overwrites the file, so open(path, "w") all by itself has removed the file and placed a new one in its place with under the exact same name?
I guess I should have thought of an overwrite as a write over.

Fine then how can I zero the bytes and bits out?

And what about open(path, "r+").write("something") and open(path, "a").write("something") won't that change the bits and bytes? Or does it just unlink the file and write a new one it its place?

unlinking bypasses the recycle bin folder?

Python only wraps the lower level system functions which open a file to create a file descriptor or a pointer to file, and the corresponding read or write functions. So, for example you could ask in the C forum if fopen() with mode 'w' physically overwrites existing contents on the drive, or if it may write in a different place.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.