在设定位置创建不可见文件夹

Creating invisible folders in a set location

我想在我的电脑上创建不可见的文件夹。

问题是如果我的子文件夹被删除,它不会更新。

如果我要添加新文件夹,除非我每次都删除C:/TVBA,否则不会更新,这是不安全的。

它还会在我的 python 脚本所在的 C:/TVBA.

处创建不可见文件夹

我该如何解决这个问题?

   try:
        rootpath = r'C:/TVBA'
        os.mkdir(rootpath)
        os.chdir(rootpath)
    except OSError:
        pass
    for sub_folder in ['1', '2', '3', '4', '5', '6']:
        try:
            os.mkdir(sub_folder)
            ctypes.windll.kernel32.SetFileAttributesW(sub_folder, 2)
        except OSError:
            pass

使用os.makedirs。相关文档是

"os.makedirs?

签名:os.makedirs(姓名,模式=511,exist_ok=False) 文档字符串: makedirs(名称[ 模式=0o777][ exist_ok=False])

创建叶目录和所有中间目录。像 mkdir,除了任何中间路径段(不仅仅是最右边的) 如果它不存在,将被创建。如果目标目录已经 存在,如果 exist_ok 为 False,则引发 OSError。否则也不例外 上调。这是递归的。"

它在您的当前文件夹中创建了不可见的文件夹,因为您没有传递 ctypes.windll.kernel32.SetFileAttributesW() 所需的路径。我的 Python 版本是 3.6,我已经在 Windows 10:

上尝试了下面的代码
import os
import ctypes

# Create a folder, make sub_folders in it and hide them
try:
    rootpath = "path/to/folder"
    os.mkdir(rootpath)
except OSError as e:
    print(e)  # So you'll know what the error is

for subfolder in ['1', '2', '3', '4', '5', '6']:
    try:
        path = rootpath + "/" + subfolder  # Note, full path to the subfolder
        os.mkdir(path)
        ctypes.windll.kernel32.SetFileAttributesW(path, 2)  # Hide folder
    except OSError as e:
        print(e)


# Remove a subfolder
os.rmdir(rootpath + "/" + "1")

# Add a new sub_folder
path = rootpath + "/" + "newsub"
os.mkdir(path)

# Hide the above newsub
ctypes.windll.kernel32.SetFileAttributesW(path, 2)

# Unhide all the sub-folders in rootpath
subfolders = os.listdir(rootpath)

for sub in subfolders:
    ctypes.windll.kernel32.SetFileAttributesW(rootpath + "/" + sub, 1)

经过运行以上代码后,rootpath中的子文件夹为:

>>> os.listdir(rootpath)
['2', '3', '4', '5', '6', 'newsub']

希望对您有所帮助。