file.truncate does this:Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position…Not quite the same as Zed's description—it only "empties the file" if the current position is the start of the file—but since we just opened the file (and not in
a mode), the current position is the start, so that isn't relevant. We're truncating to an empty file.Which is all well and good, except that
open already does that:The most commonly-used values of mode areSo, we open the file, creating it if it doesn't exist and truncating it to 0 bytes if it does. Then, on the next line, we truncate it to 0 bytes.'r'for reading,'w'for writing (truncating the file if it already exists) …
(That "Truncating the file. Goodbye!" message is pretty misleading, since we've already truncated it. Imagine you put a breakpoint on that line and decided to kill the program before executing it…)
But notice that this isn't some silly mistake by Zed; he appears to have done this specifically to make the point in study drill #5:
If you open the file with'w'mode, then do you really need thetarget.truncate()? Read the documentation for Python'sopenfunction and see if that's true.
copied form Stackflow answer.
Using truncate() we can access hidden and system files to erase data cause we cannot erase the hidden and system files' data using fp = open("file_name.txt","w") fp.write("") like this.
It can be done like this.
Why we cannot do that:
"
It's just how the Win32 API works. Under the hood, Python's
The
If you carefully read the remarks in the
open function is calling the CreateFile function, and if that fails, it translates the Windows error code into a Python IOError.The
r+ open mode corresponds to a dwAccessMode of GENERIC_READ|GENERIC_WRITE and a dwCreationDisposition of OPEN_EXISTING. The w open mode corresponds to a dwAccessMode of GENERIC_WRITE and a dwCreationDisposition of CREATE_ALWAYS.If you carefully read the remarks in the
CreateFile documentation, it says this:IfSo if you were callingCREATE_ALWAYSandFILE_ATTRIBUTE_NORMALare specified,CreateFilefails and sets the last error toERROR_ACCESS_DENIEDif the file exists and has theFILE_ATTRIBUTE_HIDDENorFILE_ATTRIBUTE_SYSTEMattribute. To avoid the error, specify the same attributes as the existing file.
CreateFile directly from C code, the solution would be to add in FILE_ATTRIBUTE_HIDDEN to the dwFlagsAndAttributes parameter (instead of just FILE_ATTRIBUTE_NORMAL).
However, since there's no option in the Python API to tell it to pass
in that flag, you'll just have to work around it by either using a
different open mode or making the file non-hidden.
No comments:
Post a Comment