[파이썬] os 권한 변경: `os.chmod()`

When working with files or directories in Python, you may need to change their permissions or access rights. The os.chmod() function from the os module provides a way to modify the permissions of a file or directory.

Understanding File Permissions

Before diving into using os.chmod(), it is important to understand file permissions on a Unix-based system. In Unix-like operating systems, every file or directory has three sets of permissions: read, write, and execute. These permissions are assigned to three entities: the owner, the group, and others.

The permission levels are denoted by the following symbols:

These permissions can be represented as a three-digit number, with each digit representing the permission for the owner, group, and others, respectively. For example, 755 means read, write, and execute permissions for the owner, while only read and execute permissions for the group and others.

Changing File Permissions with os.chmod()

The os.chmod() function allows you to modify the permissions of a file or directory using the octal representation. Here’s the syntax of the os.chmod() function:

os.chmod(path, mode)

Example: Changing File Permissions

Let’s see an example of how to use os.chmod() to change the permissions of a file:

import os

# Specify the path to the file
file_path = "/path/to/file.txt"

# Set the new permissions - Read and write for the owner, and read-only for others
new_permissions = 0o644

# Change the permissions of the file
os.chmod(file_path, new_permissions)

print("File permissions changed successfully!")

In the example above, we import the os module and specify the path to the file we want to modify permissions for. We then define the new permissions using the octal representation (0o644), which gives read and write permissions to the owner and read-only permissions to others. Finally, we call os.chmod() with the file_path and new_permissions arguments to change the permissions of the file.

Conclusion

Changing file permissions is an important aspect of file management in Python. The os.chmod() function provides a simple and effective way to modify the permissions of a file or directory. By understanding the octal representation of file permissions and using os.chmod(), you can easily customize access rights according to your needs.