Python os.lchown() 方法



Python 的lchown()方法用於更改指定檔案路徑的所有者ID (UID)和組ID (GID)。要保持其中一個ID不變,將其設定為-1。

UID和GID是與系統中每個使用者和組關聯的整數值。只有超級使用者才能更改這些ID。

語法

以下是Python lchown()方法的語法:

os.lchown(path, uid, gid)

引數

Python lchown()方法接受以下引數:

  • path - 這是需要設定所有權的檔案路徑。

  • uid - 它指定要為檔案設定的所有者ID。

  • gid - 這是要為檔案設定的組ID。

返回值

Python lchown()方法不返回值。

示例

以下示例演示了lchown()方法的用法。在這裡,我們正在更改單個檔案的所有者ID和組ID。

#!/usr/bin/python
import os, sys

# Open a file
path = "foo.txt"
fd = os.open( path, os.O_RDWR|os.O_CREAT )

# Close opened file
os.close( fd )

# Setting file owner ID
os.lchown( path, 500, -1)

# Set a file group ID
os.lchown( path, -1, 500)
print ("Ownership Changed Successfully!!")

執行以上程式時,會產生以下結果:

Ownership Changed Successfully!!

示例

在以下示例中,我們使用lchown()方法一次更改多個檔案的所有者ID和組ID。

import os

# List of file paths
filePaths = ["txtFile.txt", "/home/TP/Python/tmp/new/monthly", "/home/TP/Python/tmp/"]

# setting UID and GID
user_id = 501
group_id = 21

# Changing ownership for each file
for path in filePaths:
   os.lchown(path, user_id, group_id)

print("Ownership successfully changed")

執行以上程式後,會產生以下輸出:

Ownership successfully changed
python_files_io.htm
廣告