[파이썬] os 파일 경로 결합: `os.path.join()`

To use os.path.join(), you need to import the os module in your Python script. Here’s an example of how to use os.path.join() to combine file path components:

import os

# Define the file path components
directory = "documents"
filename = "file.txt"

# Combine the path components using os.path.join()
file_path = os.path.join(directory, filename)

# Print the combined file path
print(file_path)

Output:

documents/file.txt  # or documents\file.txt on Windows

In the above example, the os.path.join() method is used to combine the directory and filename variables into a single file path. The resulting file path is then printed to the console.

By using os.path.join() instead of manually concatenating path components using strings, you ensure that the resulting path will be correct and compatible with the operating system you are running the Python script on.

Keep in mind that os.path.join() can accept multiple arguments. For example, if you have multiple subdirectories within the main directory, you can pass them as separate arguments to os.path.join():

import os

# Define the path components
main_directory = "documents"
subdirectory1 = "folder1"
subdirectory2 = "folder2"
filename = "file.txt"

# Combine the path components using os.path.join()
file_path = os.path.join(main_directory, subdirectory1, subdirectory2, filename)

# Print the combined file path
print(file_path)

Output:

documents/folder1/folder2/file.txt  # or documents\folder1\folder2\file.txt on Windows

In the above example, os.path.join() is used to combine four path components: main_directory, subdirectory1, subdirectory2, and filename.

Using os.path.join() allows you to easily manage file paths in a cross-platform way, ensuring your code works correctly regardless of the operating system.