SYSTEM NOTICE

Auto translation by AI. Be sure, accuracy, nuances and authorial intent may not be fully reflected.
見出し画像

Step 13: Basics of File Operations ① - Reading and Writing Text Files

From here on, we will enter a new theme to make programs more useful: File Operations.
Programs do not just perform calculations or display output.
By reading and writing external files, you can save and utilize data, which gives you a glimpse into a future where you can finally build actual applications. Therefore, "input/output" is a very important fundamental.

This time, we will first learn about reading and writing text files (.txt) and file modes.



1. Basics of File Operations

When handling files in Python, the following flow is standard.

  1. Open file (open)

  2. Read/Write

  3. Close (close)


2. Opening a File (open function)

f = open("sample.txt", "w")  # ファイルを開く
f.write("Hello, world!")     # ファイルに書き込む
f.close()                    # ファイルを閉じる

When executed, "sample.txt" will be created in the same folder where this program is saved, and "Hello, world!" will be written inside it.


3. What are File Modes?

The second argument of open() specifies the mode.
Depending on the mode, the behavior such as "write" or "read" changes.


4. Reading a File

To read the content you have written, use the "r" mode.

f = open("sample.txt", "r")  # 読み取りモードで開く
data = f.read()              # 中身をすべて読む
f.close()

print(data)

5. Using the with statement is convenient

When performing file input/output, we have been writing code that starts with open and ends with close, but actually, if you use "with" as shown below, it will automatically close the file for you, which is convenient.

with open("sample.txt", "w") as f:
    f.write("こんにちは!")

with open("sample.txt", "r") as f:
    data = f.read()
    print(data)

6. Why are file operations important?

  • Data can be saved: Data does not disappear even after the program ends

  • Data can be shared: Can interact with other people or other programs

  • Apps can grow: Can handle settings, records, and logs

Next time, let's proceed to learn about CSV files, which handle more structured data.
Using CSV files allows you to easily save and load tabular data.


Practice Exercises

  1. Create a file named memo.txt and write your favorite sentence into it.

  2. Read the created memo.txt file and display it on the screen.

  3. Add a new line in 'a' mode and display it again.

  4. Rewrite the same process more concisely using the 'with' statement.

  5. Create a program that displays the length (number of characters) of the read string.


Summary

  • You can open files with open() and read/write with read() / write().

  • Learn the modes "w", "a", and "r".

  • Using 'with' prevents forgetting to close the file.

Next time, we will learn about reading and writing CSV files and the importance of data management for programs!

Next Article


いいなと思ったら応援しよう!

DOI@日々学びの本質を考え続ける探求者 よろしければ応援お願いします! いただいたチップは引き続きプログラミングや学びについて、皆さんの利益になるようなよい記事を書くことで恩返しをさせていただきます!