在Windows中克隆文件属性

时间:2018-06-02 12:12:17

标签: python windows python-3.x

我正在尝试使用一个小的python脚本来克隆文件夹及其内容,但是我遇到了一个小问题 - 当我复制一个隐藏文件或系统文件时,复制的文件会丢失这些属性。

我知道我可以使用os.stat(original_file).st_file_attributeswin32api.GetFileAttributes(original_file)来获取文件属性,并且我可以使用win32api.SetFileAttributes()来设置目标文件的属性,如果,对于例如,我测试stat.FILE_ATTRIBUTE_HIDDEN

问题在于,我不知道如何直接使用win32api.GetFileAttributes() win32api.SetFileAttributes()的完整结果。完整结果我指的是所有文件属性。

为了更清楚,我想要实现的目标是:

  1. original_file
  2. 获取文件属性
  3. 将文件属性设置为target_file
  4. 这可以一次性使用还是我必须单独测试每个文件属性?

2 个答案:

答案 0 :(得分:0)

有一个名为attrib的命令。它将属性添加到文件中。

attrib <attributes> <file directory>

您可以使用以下格式添加属性:

'+h' makes file hidden
'+r' makes file read only

等等。

因此我们会像这样使用它来使文​​件隐藏和只读 attrib +h +r <file directory>

所以将列表中的所有属性都放在attrib命令的格式中。使用os.system()执行命令。

答案 1 :(得分:0)

首先,非常感谢您的快速回复。你让我思考了一点......长话短说,我傻了!我想要的(克隆文件属性)可以简单地实现:

import win32api

file1 = 'D:\\_test_fs1\\file1.txt' # hidden and system file (attrib +h +s file1.txt)
file2 = 'D:\\_test_fs2\\copy_of_file1.txt' # non-hidden and non-system file (attrib -h -s copy_of_file1.txt)

f1a = win32api.GetFileAttributes(file1)
f2a = win32api.GetFileAttributes(file2)

if f1a == f2a:
    print('The files have the same attributes (f1: %i) (f2: %i).' % (f1a, f2a))
    print('Nothing to do.')
else:
    print('The files DO NOT have the same attributes (f1: %i) (f2: %i)!' % (f1a, f2a))
    win32api.SetFileAttributes(file2, f1a) # Setting file2 to have the same exact attributes as file1
    print('Attributes in f2 set.')

感谢您的关注!