python中文件的权限更改

时间:2011-08-29 09:22:29

标签: python

我想更改当前目录树中所有文件的文件权限。我正在尝试打开每个目录并打开文件并使用os.chmod()更改权限,但收到错误。

import os
import stat

for files in os.walk('.'):
        os.chmod(files,stat.S_IXGRP)

我得到的错误是:

File "delhis.py", line 4, in ? os.chmod(files,stat.S_IXGRP) TypeError: coercing to Unicode: need string or buffer, tuple found

3 个答案:

答案 0 :(得分:28)

您错误地使用了os.walk

for dirpath, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        path = os.path.join(dirpath, filename)
        os.chmod(path, 0o777) # for example

答案 1 :(得分:0)

您可以改为使用OS特定的函数调用,如下所示:

os.system('chmod 777 -R *')

答案 2 :(得分:0)

如果您只想让文件对所有人开放,您可以使用以下课程:

import win32security
import ntsecuritycon

class Win32FileSecurityMod:
  def __init__(self):
    self.security_dict = {}
    # return tuple from LookupAccountName() is user, domain, type
    self.security_dict["Everyone"] = win32security.LookupAccountName("", "Everyone")
    self.security_dict["Administrators"] = win32security.LookupAccountName("", "Administrators")
    self.security_dict["CurrentUser"] = win32security.LookupAccountName("", win32api.GetUserName())
    self.admins = self.security_dict["Administrators"][0]
    self.everyone = self.security_dict["Everyone"][0]
    self.user = self.security_dict["CurrentUser"][0]

  def SetPromiscuousFileAccess(self, file_path):
    print(file_path)
    con = ntsecuritycon
    sd = win32security.GetFileSecurity(file_path,win32security.DACL_SECURITY_INFORMATION)
    dacl = win32security.ACL()
    # con.FILE_GENERIC_READ
    # con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE,
    # con.FILE_ALL_ACCESS
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, self.everyone)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, self.user)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, self.admins)
    # Put our new DACL into the Security Descriptor,
    # update the file with the updated SD, and use
    # CACLS to show what's what.
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION, sd)

  # Gets the attributes of the file by executing a shell command. Useful for testing
  # but it will have performance problems for large file sets.
  def GetCacls(self, file_path):
    out = []
    for line in os.popen("cacls %s" % file_path).read().splitlines():
      out.append(line)
    return out