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

2024-09-25 18:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在我的电脑上创建不可见的文件夹

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

如果我想添加新文件夹,它将不会更新,除非我每次都删除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

Tags: in脚本文件夹forospassfoldertry
2条回答

它在当前文件夹中创建了不可见的文件夹,因为您没有传递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中的子文件夹是:

^{pr2}$

希望有帮助。在

使用操作系统makedirs. 相关文件是

““是什么意思?在

签字:操作系统makedirs(名称,模式=511,exist\U ok=False) 文档字符串: makedirs(名称[,模式=0o777][,exist_ok=False])

创建一个叶目录和所有中间目录。工作原理 mkdir,除了任何中间路径段(不仅仅是最右边的) 将在不存在的情况下创建。如果目标目录已经 exists,如果exist\u ok为False,则引发OSError。否则也不例外 提高。这是递归的。”

相关问题 更多 >