+ 1

How to delete files in Python3

13th Jul 2017, 7:04 AM
Дима Дараган
Дима Дараган - avatar
8 Réponses
+ 13
#off the top of my head... import os os.remove("filepath\\thing.txt") #that may be wrong though
13th Jul 2017, 7:10 AM
Ahri Fox
Ahri Fox - avatar
+ 7
what's a unit? like, a unit of troops?!
13th Jul 2017, 8:11 AM
Ahri Fox
Ahri Fox - avatar
+ 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
13th Jul 2017, 9:15 PM
Kirk Schafer
Kirk Schafer - avatar
+ 5
yes, os, which is used in my example, is in-built
13th Jul 2017, 11:15 AM
Ahri Fox
Ahri Fox - avatar
+ 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.
13th Jul 2017, 8:59 AM
Igor B
Igor B - avatar
0
How to delete without units
13th Jul 2017, 7:41 AM
Дима Дараган
Дима Дараган - avatar
0
library
13th Jul 2017, 8:16 AM
Дима Дараган
Дима Дараган - avatar
0
Maybe exist in-buildt method or instruction
13th Jul 2017, 9:01 AM
Дима Дараган
Дима Дараган - avatar