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.9k times
3 Answers
20
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"])
for a full cross-platform solution see Python cross platform hidden file

Jean-François Fabre
- 137,073
- 23
- 153
- 219
5
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
- 137,073
- 23
- 153
- 219

zipa
- 27,316
- 6
- 40
- 58
-
7You'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
-
Here is one doing this WITHOUR 3rdparty lib but builtin `ctypes`: https://stackoverflow.com/a/19622903/469322 – ewerybody Sep 01 '23 at 13:43
5
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 Ħậꞣǐɱ
- 180
- 1
- 6
-
`os.system` is obsolescent, and you have to protect the name of your file if it has spaces in it. – Jean-François Fabre Oct 06 '22 at 12:19