[파이썬] 파일 경로와 파일 액세스 제한

Python is a powerful programming language that provides various ways to work with files and directories. In this blog post, we will explore different methods to handle file paths and discuss how to restrict file access in Python.

파일 경로 (File Paths)

File paths are used to specify the location of a file within a file system. Python provides the os module, which offers functions for working with file paths. Here’s an example of how to use the os module to manipulate file paths:

import os

# Get the current working directory
current_dir = os.getcwd()
print("Current directory: ", current_dir)

# Join path components
path1 = 'documents'
path2 = 'files.txt'
file_path = os.path.join(current_dir, path1, path2)
print("File path: ", file_path)

# Split the file path
dir_name, file_name = os.path.split(file_path)
print("Directory name: ", dir_name)
print("File name: ", file_name)

The above code demonstrates how to get the current working directory, combine multiple path components using os.path.join(), and split a file path into directory name and file name using os.path.split().

파일 액세스 제한 (File Access Restriction)

In some cases, it may be necessary to restrict access to certain files for security or privacy reasons. Python’s os module provides functions to set file permissions and check for file accessibility.

To set file permissions, you can use the os.chmod() function. Here’s an example:

import os

# Set file permission - read, write, execute for owner and group
file_path = 'path/to/file.txt'
os.chmod(file_path, 0o775)

In the above code, we set the file permissions of file.txt to read, write, and execute for the owner and group.

To check the accessibility of a file, you can use the os.access() function. Here’s an example:

import os

# Check if file is readable
file_path = 'path/to/file.txt'
if os.access(file_path, os.R_OK):
    print("File is readable.")
else:
    print("File is not readable.")

The above code checks if the file file.txt is readable. Alternatively, you can use os.W_OK to check if the file is writable or os.X_OK to check if it is executable.

By manipulating file permissions and checking file accessibility, you can effectively restrict access to files in your Python programs.

결론 (Conclusion)

In this blog post, we discussed how to work with file paths and restrict file access in Python. Python’s os module provides functions to manipulate file paths, set file permissions, and check for file accessibility. Understanding these concepts is essential for managing and securing files and directories in Python applications.

Remember to handle file access restrictions with caution and adhere to security best practices to protect sensitive data and ensure the integrity of your Python programs.