Concept Flow - File system interaction basics
Start
Open file
Read/Write file
Close file
End
The program opens a file, reads or writes data, then closes the file to finish.
with open('example.txt', 'w') as f: f.write('Hello!') with open('example.txt', 'r') as f: content = f.read() print(content)
| Step | Action | File Mode | File Content Before | File Content After | Output |
|---|---|---|---|---|---|
| 1 | Open file 'example.txt' for writing | w | '' (empty) | '' (empty) | |
| 2 | Write 'Hello!' to file | w | '' (empty) | 'Hello!' | |
| 3 | Close file after writing | w | 'Hello!' | 'Hello!' | |
| 4 | Open file 'example.txt' for reading | r | 'Hello!' | 'Hello!' | |
| 5 | Read content from file | r | 'Hello!' | 'Hello!' | |
| 6 | Print content | r | 'Hello!' | 'Hello!' | Hello! |
| 7 | Close file after reading | r | 'Hello!' | 'Hello!' |
| Variable | Start | After Step 2 | After Step 5 | Final |
|---|---|---|---|---|
| f (file object) | None | Open for write | Open for read | Closed |
| content | None | None | 'Hello!' | 'Hello!' |
Open a file with open(filename, mode): 'r' to read, 'w' to write (clears file), 'a' to append Use with to auto-close files Read with read(), write with write() Always close files to save and free resources