Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cross platform hidden file

Tags:

python

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.

like image 274
Nick Humrich Avatar asked Aug 21 '14 17:08

Nick Humrich


People also ask

How do I show hidden files in Python?

Select the Start button, then select Control Panel > Appearance and Personalization. Select Folder Options, then select the View tab. Under Advanced settings, select Show hidden files, folders, and drives, and then select OK.

How do I see hidden files in Linux?

To show hidden files you must use the -a option, which commands ls to list "all" files and folders (including hidden ones). Navigate to your home directory with the cd command and do a listing of all files using ls. As you can see, there are several files that start with a dot (.).

How do you show hidden files on Mac?

Showing hidden files via Mac FinderPress the “Command” + “Shift” + “.” (period) keys at the same time. The hidden files will show up as translucent in the folder. If you want to obscure the files again, press the same “Command” + “Shift” + “.” (period) combination.


1 Answers

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:

  • How do I check if I'm running on Windows in Python?
  • Set "hide" attribute on folders in windows OS?
like image 169
luke Avatar answered Oct 09 '22 16:10

luke