[파이썬] 파일의 디렉토리 내 파일 읽기와 쓰기

Introduction

Working with files is a common task in many programming projects. In Python, you can read and write files easily using the built-in functions and libraries. In this blog post, we will explore how to read and write files within a directory in Python.

Reading Files

To read a file within a specific directory, you can use the open() function in Python. Let’s assume we have a file named “example.txt” located in the “files” directory. Here’s an example of how to read the contents of this file:

with open("files/example.txt", "r") as file:
    contents = file.read()
    print(contents)

In the code above, we use the open() function to open the file in read mode ("r") and assign it to a file object called file. The with statement ensures that the file is automatically closed after we finish reading it. We then use the read() method to read the entire contents of the file and print it.

Writing Files

To write data to a file within a directory, we can use the open() function once again, but this time in write mode ("w"). Let’s create a new file named “output.txt” and write some text into it:

with open("files/output.txt", "w") as file:
    file.write("Hello, World!")

In the code above, we open the file “output.txt” within the “files” directory in write mode. We use the write() method of the file object to write the text “Hello, World!” into the file. Note that if the file doesn’t exist, it will be created automatically.

Conclusion

Reading and writing files within a directory in Python is straightforward. By using the open() function with the appropriate mode, we can easily read the contents of a file or write data into a new file. Remember to always close the file after you finish reading or writing to it to free up system resources.