[파이썬] 파일 경로와 하위 파일 목록 조회

In this blog post, we will explore how to retrieve the file path and list all the subfiles present within a given directory in Python. The ability to access and manipulate file paths is an essential task for many software applications and data processing tasks.

Retrieving File Paths

To retrieve the file path of a directory, we can make use of the os module in Python. This module provides a range of functions for interacting with the operating system, including file and directory manipulation.

import os

# Specify the directory path
directory = '/path/to/directory'

# Get the file path of the directory
file_path = os.path.realpath(directory)

# Print the file path
print(file_path)

In the code snippet above, replace /path/to/directory with the actual path of the directory you want to retrieve the file path for. The os.path.realpath() function returns the canonical path of the specified directory.

Listing Subfiles

Once we have the file path of the directory, we can list all the subfiles present within it. We will use the os.listdir() function to retrieve a list of all the files and directories inside the specified path.

import os

# Specify the directory path
directory = '/path/to/directory'

# List all the subfiles
subfiles = os.listdir(directory)

# Print the subfiles
for file in subfiles:
    print(file)

Replace /path/to/directory with the actual path of the directory for which you want to list the subfiles. The os.listdir() function returns a list of file names and directory names present within the specified path.

Conclusion

Being able to retrieve the file path of a directory and list its subfiles is fundamental to many file handling operations in Python. With the help of the os module, we can easily accomplish these tasks and create powerful file management systems or data processing pipelines.

Remember to import the os module before using its functions, and make sure to provide the correct directory path to retrieve the desired results.