Concept Flow - Why file handling matters
Start Program
Open File
Read/Write Data
Close File
Use Data in Program
End Program
This flow shows how a program opens a file, reads or writes data, closes the file, and then uses that data.
file = File.open('data.txt', 'w') file.puts('Hello, world!') file.close file = File.open('data.txt', 'r') content = file.read file.close
| Step | Action | File State | Variable Values | Output |
|---|---|---|---|---|
| 1 | Open file 'data.txt' for writing | Open for write | file = File object | |
| 2 | Write 'Hello, world!' to file | Open for write | file = File object | Writes text to file |
| 3 | Close file | Closed | file = File object | |
| 4 | Open file 'data.txt' for reading | Open for read | file = File object | |
| 5 | Read content from file | Open for read | content = 'Hello, world!' | |
| 6 | Close file | Closed | file = File object, content = 'Hello, world!' |
| Variable | Start | After Step 2 | After Step 5 | Final |
|---|---|---|---|---|
| file | nil | File object (write mode) | File object (read mode) | File object (closed) |
| content | nil | nil | 'Hello, world!' | 'Hello, world!' |
File handling lets programs save and load data. Open a file to read or write. Always close the file to save changes and free resources. Use the data after reading. Skipping close can cause data loss.