Skip to content

Instantly share code, notes, and snippets.

@sgornick
Created August 14, 2023 23:15
Show Gist options
  • Save sgornick/6acb6974370da98f3b3c578d780c0728 to your computer and use it in GitHub Desktop.
Save sgornick/6acb6974370da98f3b3c578d780c0728 to your computer and use it in GitHub Desktop.
Hold a file open exclusively, not even accessible for reading (Python)
Hold a file open exclusively, not even for reading (PowerShell)import os, win32file
while True:
try:
filename_and_path = input("Enter filename and path for the file to hold open exclusively: ")
if not os.path.isabs(filename_and_path):
# If relative path, convert it to an absolute path
filename_and_path = os.path.abspath(filename_and_path)
if os.path.exists(filename_and_path):
break
print("File not found. Please provide a valid filename.")
continue
except KeyboardInterrupt:
print()
print("Keyboard interrupt. Exiting...")
exit()
except FileNotFoundError:
print("File not found. Please provide a valid filename.")
continue
try:
# Open the file in exclusive mode
handle = win32file.CreateFile(
filename_and_path,
win32file.GENERIC_READ,
0,
None,
win32file.OPEN_EXISTING,
win32file.FILE_ATTRIBUTE_NORMAL,
None
)
try:
print()
print(f"Holding open, exclusively: {filename_and_path}")
input("Press enter to continue...")
finally:
win32file.CloseHandle(handle)
except win32file.error as e:
if e.winerror == 32:
print(f"Error opening file: {e.strerror} ({e.winerror})")
os.sys.exit(1)
@sgornick
Copy link
Author

sgornick commented Aug 14, 2023

The "easy" methods to lock a file exclusively (like doing the command C:> Pause > test.txt ), still permit reading. This script is mean to lock the file exclusively and prevent even reading.

Requires the pywin32 module.

For the equivalent of this script, but in PowerShell see:

https://gist.github.com/sgornick/d6072ef254bfe58f18ffd53b78ae0e7a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment