[파이썬] 파일 경로의 생성 및 삭제

Python provides a simple and powerful way to manipulate files and directories. In this blog post, we will explore how to create and delete file paths using Python.

Creating a File Path

To create a file path using Python, we can utilize the os module from the standard library. The os module provides various functions for interacting with the operating system. Specifically, we will use the os.path.join() function to create a file path.

Here is an example of creating a file path:

import os

directory = "path/to/directory"
filename = "file.txt"

file_path = os.path.join(directory, filename)
print(file_path)

In the above code, we specify the directory and filename. Then, we use the os.path.join() function to combine them and create the file path. Finally, we print the file path.

The output will be:

path/to/directory/file.txt

Deleting a File Path

To delete a file path in Python, we can use the os module’s os.remove() function. This function allows us to delete files by providing the file path as an argument.

Here is an example of deleting a file path:

import os

file_path = "path/to/file.txt"

if os.path.exists(file_path):
    os.remove(file_path)
    print("File deleted successfully.")
else:
    print("File does not exist.")

In the above code, we check if the file path exists using the os.path.exists() function. If the file exists, we proceed to delete it using the os.remove() function. Otherwise, we display a message indicating that the file does not exist.

Please note that the os.remove() function permanently deletes the file and it cannot be recovered.

Conclusion

In this blog post, we learned how to create and delete file paths using Python. By utilizing the os module, we can easily handle file operations. Whether it is creating a file path or deleting it, Python provides convenient functions to perform these tasks.