Python os.fchmod()

Python os.fchmod()

Python os.fchmod() 方法用于将指定文件描述符给出的文件模式更改为指定的数字模式。这个方法等价于 os.chmod(fd, mode) .
注意:此方法仅在Unix平台上可用。

语法:os.fchmod(fd, mode)

参数:

fd:要设置其模式的文件描述符。

mode:表示要设置的模式的数值。

mode 也可以取下列值之一或它们的位或组合:

  • @S_ISUID:设置执行时的用户ID
  • @S_ISGID:在执行时设置组ID
  • @S_ENFMT:执行记录锁定
  • @S_ISVTX:执行后保存文本图像
  • stat.S_IREAD:由所有者阅读。
  • stat.S_IWRITE:由所有者写入。
  • @S_IEXEC:由所有者执行。
  • stat.S_IRWXU:由所有者进行读、写和执行
  • stat.S_IRUSR:由所有者阅读
  • stat.S_IWUSR:所有者写入。
  • @S_IXUSR:由所有者执行。
  • stat.S_IRWXG:按组读、写和执行
  • stat.S_IRGRP:按组读
  • stat.S_IWGRP:按组写
  • stat.S_IXGRP:按组执行
  • stat.S_IRWXO:由其他人读取、写入和执行。
  • stat.S_IROTH:其他人读
  • stat.S_IWOTH:别人写
  • stat.S_IXOTH:被其他人执行

返回类型:此方法不返回任何值。

示例1

使用os.fchmod()方法

# 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程