13
votes

In *nix I can simply add a . to a file to make it "hidden". There are also ways to make a file hidden in windows.

Is there a way in python to make a file hidden CROSS PLATFORM?

currently:

def write_hidden(file_name, data):
    file_name = '.' + file_name
    with open(file_name_, 'w') as f:
        f.write(data)

But as I said, that only works with *nix systems.

1
No, there is not a single cross-platform way to create a hidden file, because different operating systems have entirely different implementations. The Windows version basically requires a chattr() call, whereas the UNIX version modifies filenames... how would anyone even create a single abstraction that could reasonably do both those things? - Charles Duffy
If your question was how to make a hidden file on Windows from Python, you'd have a better chance of getting an answer. You're not going to find a single abstraction that does both. - Charles Duffy
This has nothing to do with Python, really, as this is a OS-level problem. A solution that works in Python will work in Perl, Ruby, C, etc. - Martijn Pieters♦

1 Answers

10
votes

You could do something like this:

import os
import ctypes

FILE_ATTRIBUTE_HIDDEN = 0x02

def write_hidden(file_name, data):
    """
    Cross platform hidden file writer.
    """
    # For *nix add a '.' prefix.
    prefix = '.' if os.name != 'nt' else ''
    file_name = prefix + file_name

    # Write file.
    with open(file_name, 'w') as f:
        f.write(data)

    # For windows set file attribute.
    if os.name == 'nt':
        ret = ctypes.windll.kernel32.SetFileAttributesW(file_name,
                                                        FILE_ATTRIBUTE_HIDDEN)
        if not ret: # There was an error.
            raise ctypes.WinError()

This has not been tested but should work fine.

Also you may wish to see these other questions that helped me implement this: