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.
Jump into concepts and practice - no test required
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.
open('file.txt', 'r') command do in Python?open() function is used to open a file in a specified mode.with?open(filename, mode) as variable to assign the file object.file.read() reads all content.with open('example.txt', 'r') as f:
lines = f.readlines()
print(lines)readlines() reads all lines into a list, each line ending with a newline character '\n' except possibly the last.file = open('notes.txt', 'r')
for line in file.read():
print(line)
file.close()file.read() which returns a single string of the whole file content.file.readlines() or iterate directly on file.line.strip() removes spaces and newline characters from both ends. The condition if line.strip() filters out empty lines.