On windows you can right-click a file, click on properties and select hidden. How can I do this to a file in python?
Asked
Active
Viewed 1.4k times
10
-
4Possible duplicate of [Python cross platform hidden file](http://stackoverflow.com/questions/25432139/python-cross-platform-hidden-file) – lmiguelvargasf Apr 16 '17 at 20:40
-
1Use `cmd` according to [this](http://stackoverflow.com/questions/5486725/how-to-execute-a-command-prompt-command-from-python) question and try `attrib +h PathToFile` – Xaqron Apr 16 '17 at 20:41
-
@Xaqron, it's `attrib.exe`. It's not a built-in command of the cmd shell. – Eryk Sun Apr 17 '17 at 02:17
-
@lmiguelvargasf Sometimes i would like just a short answer :) – Jared Parker Apr 17 '17 at 08:37
3 Answers
14
If you don't want/don't have access to win32 modules you can still call attrib:
import subprocess
subprocess.check_call(["attrib","+H","myfile.txt"])
Jean-François Fabre
- 131,796
- 23
- 122
- 195
6
If this is for Windows only:
import win32con, win32api
file = 'myfile.txt' #or full path if not in same directory
win32api.SetFileAttributes(file,win32con.FILE_ATTRIBUTE_HIDDEN)
Jean-François Fabre
- 131,796
- 23
- 122
- 195
zipa
- 26,044
- 6
- 38
- 55
-
5You're replacing the existing file attributes. It has to be bitwise ORd into the existing attributes from `GetFileAttributes`. – Eryk Sun Apr 17 '17 at 02:16
-
1Just to point out that `win32api` (from the 3rd-party `pywin32` package) is only required for *writing* file attributes (as done here). For *reading* file attributes, the standard library offers `os.stat().st_file_attributes`, or `pathlib.Path.stat()`, and e.g. `stat.FILE_ATTRIBUTE_HIDDEN`. Too bad [os.chflags()](https://docs.python.org/3/library/os.html#os.chflags) is not available for windows.. – djvg Jan 19 '22 at 17:08
6
this is the easy way
import os
os.system( "attrib +h myFile.txt" )
hide file '+h'
show file '-h'
myFile.txt can be the full path to your file
Ḉớᶑẽr Ħậꞣǐɱ
- 144
- 1
- 5