+ 1
How to delete files in Python3
8 Answers
+ 13
#off the top of my head...
import os
os.remove("filepath\\thing.txt")
#that may be wrong though
+ 7
what's a unit? like, a unit of troops?!
+ 6
https://code.sololearn.com/clwcMjR778n5/?ref=app
This scans for how Python's doing 'remove'. There's a little hand-waving after importing nt (because it's native) but the source for Python itself is linked at bottom. Python does not appear to have a built-in native function...it just asks the OS to do it. Without leveraging imports (like os, subprocess or ctypes, even custom C and ASM) you're probably looking at writing your own interface and breaking portability.
You could just truncate the file without an import:
open("file_to_zero.txt", "w") # it's truncated
Or...if "no imports" is because try..catch is messy + a possible race condition, here's a Pythonic delete:
import os, contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
LINKS ==========================
Python source code, after following "nt" for "remove()" on Windows:
On Windows, the file calls itself 'nt':
https://hg.python.org/cpython/file/a3f8c5d172b4/Modules/posixmodule.c
unlink(), remove(), Py_DeleteFileW():
https://hg.python.org/cpython/file/tip/Modules/posixmodule.c#l4205
https://hg.python.org/cpython/file/tip/Modules/posixmodule.c#l4250
https://hg.python.org/cpython/file/tip/Modules/posixmodule.c#l4165
Windows kernel32: DeleteFile (A: ANSI, W: wide/unicode)
https://msdn.microsoft.com/en-us/library/aa363915(VS.85).aspx
+ 5
yes, os, which is used in my example, is in-built
+ 1
"os" module is part of the standard Python library. So, while it does require an import, you don't need to install anything extra.
0
How to delete without units
0
library
0
Maybe exist in-buildt method or instruction