Created
August 14, 2023 23:15
-
-
Save sgornick/6acb6974370da98f3b3c578d780c0728 to your computer and use it in GitHub Desktop.
Hold a file open exclusively, not even accessible for reading (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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