[파이썬] os 파일 및 디렉토리 목록 조회: `os.listdir()`

When working with files and directories in Python, it’s often necessary to retrieve a list of files and directories present in a particular directory. The os module in Python provides the listdir() function for this purpose.

The os.listdir() function returns a list containing the names of the entries in the specified directory. These entries can be files, directories, or other types of entities present in the directory.

To use the os.listdir() function, we first need to import the os module:

import os

Now, let’s see some examples that demonstrate the usage of os.listdir():

Example 1: List files and directories in the current directory

In this example, we will retrieve a list of files and directories present in the current directory.

import os

entries = os.listdir()

for entry in entries:
    print(entry)

The above code will print the names of all files and directories present in the current directory.

Example 2: List files and directories in a specific directory

To list the files and directories in a specific directory, provide the path of the directory as a parameter to os.listdir().

import os

directory = '/path/to/directory'

entries = os.listdir(directory)

for entry in entries:
    print(entry)

Replace '/path/to/directory' with the actual path of the directory you want to list the files and directories for.

Example 3: Filter files only

If you want to retrieve only the files from the list of entries and exclude directories and other types of entities, you can use a simple if condition to filter them.

import os

directory = '/path/to/directory'

entries = os.listdir(directory)

for entry in entries:
    if os.path.isfile(os.path.join(directory, entry)):
        print(entry)

The above code will only print the names of files present in the specified directory. It uses the os.path.isfile() function to check if an entry is a file.

Conclusion

The os.listdir() function in Python is a convenient way to retrieve a list of files and directories in a particular directory. By using this function, you can easily obtain the necessary information about the files and directories present in a directory for further processing or analysis.

Remember to import the os module before using os.listdir(), and specify the directory path when needed. Additionally, you can use additional conditions or filters to manipulate the list of entries as per your requirements.