【问题标题】:Creating invisible folders in a set location在设定的位置创建不可见的文件夹
【发布时间】:2018-06-04 18:59:58
【问题描述】:

我正在尝试在我的电脑上创建隐形文件夹。

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

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

【问题讨论】:

    标签: python python-3.x file hide glob


    【解决方案1】:

    使用 os.makedirs。相关文档是

    "os.makedirs?

    签名:os.makedirs(name, mode=511, exists_ok=False) 文档字符串: makedirs(name [, mode=0o777][, exists_ok=False])

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

    【讨论】:

      【解决方案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中的子文件夹为:

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

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-09
        • 1970-01-01
        • 1970-01-01
        • 2019-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多