Concept Flow - Reading file data
Open file with open()
Read data from file
Store data in variable
Close file automatically
Use or print data
Open a file, read its contents into a variable, then automatically close the file to free resources.
with open('data.txt', 'r') as file: content = file.read() print(content)
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Open file 'data.txt' in read mode | File opened successfully | File object created and assigned to 'file' |
| 2 | Read entire content from file | Read operation | Content stored in variable 'content' |
| 3 | Exit with-block | File automatically closed | File resource freed |
| 4 | Print content | Output content to screen | Content of 'data.txt' displayed |
| 5 | End of program | No more code | Program stops |
| Variable | Start | After Step 2 | Final |
|---|---|---|---|
| file | None | File object (open) | File object (closed) |
| content | None | File content as string | File content as string |
Reading file data in Python: Use 'with open(filename, mode) as var:' to open files safely. Read all content with 'var.read()'. File closes automatically after the block. Print or use the read data stored in a variable.