📜  Python| os.fchmod() 方法

📅  最后修改于: 2022-05-13 01:55:16.087000             🧑  作者: Mango

Python| os.fchmod() 方法

Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
在类 Unix 系统中,模式是授予用户、组和其他类访问文件的文件系统权限。
Python中的os.fchmod()方法用于将指定文件描述符给定的文件的模式更改为指定的数字模式。此方法等效于os.chmod(fd, mode)
注意:此方法仅适用于 Unix 平台。

代码: os.fchmod() 方法的使用

Python3
# Python program to explain os.fchmod() method
 
# importing os module
import os
 
# importing stat module
import stat
 
# File name
filename = "file.txt"
 
# Open the specified file and
# get the file descriptor
# associated with it using
# os.open() method
fd = os.open(filename, os.O_RDWR)
 
 
# Print the current numeric mode
# (octal notation ) of the file
mode = oct(os.stat(fd).st_mode)[-3:]
print("Current numeric mode of the file (octal notation):", mode)
 
 
# Now change the mode
# of the file
 
# octal value 777 as mode means
# read write and execute permission
# for owner, group and others
mode = 0o777
os.fchmod(fd, mode)
print("\nFile mode changed successfully")
 
# Print the changed numeric mode
# (octal notation ) of the file
mode = oct(os.stat(fd).st_mode)[-3:]
print("Current numeric mode of the file (octal notation):", mode)
 
 
# mode parameter can be also
# given by flags defined in
# stat module
 
# Change mode
mode = stat.S_IRWXU
os.fchmod(fd, mode)
print("\nFile mode changed successfully")
print("Now, File can be read, write and executed by owner only")
 
# Print the changed numeric mode
# (octal notation ) of the file
mode = oct(os.stat(fd).st_mode)[-3:]
print("Current numeric mode of the file (octal notation):", mode)
 
 
 
# change mode
mode = stat.S_IRWXU | stat.S_IRGRP
os.fchmod(fd, mode)
print("\nFile mode changed successfully")
print("Now, File can be read, write and executed \
by owner but can be read by group")
 
# Print the changed numeric mode
# (octal notation ) of the file
mode = oct(os.stat(fd).st_mode)[-3:]
print("Current numeric mode of the file (octal notation):", mode)
 
 
# Close the file descriptor
os.close(fd)


输出:
Current numeric mode of the file (octal notation): 666

File mode changed successfully
Current numeric mode of the file (octal notation): 777

File mode changed successfully
Now, File can be read, write and executed by owner only
Current numeric mode of the file (octal notation): 700

File mode changed successfully
Now, File can be read, write and executed by owner but can be read by group
Current numeric mode of the file (octal notation): 740