简体   繁体   中英

Python cross platform hidden file

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM