Concept Flow - Working with CSV files
Open CSV file
Create CSV reader
Read each row
Process row data
Close file
This flow shows how Python opens a CSV file, reads it row by row, processes the data, and then closes the file.
import csv with open('data.csv', newline='') as file: reader = csv.reader(file) for row in reader: print(row)
| Step | Action | Code Line | Variable State | Output |
|---|---|---|---|---|
| 1 | Open file 'data.csv' for reading | with open('data.csv', newline='') as file: | file=open | |
| 2 | Create CSV reader object | reader = csv.reader(file) | reader=csv.reader object | |
| 3 | Read first row | for row in reader: | row=['Name', 'Age', 'City'] | ['Name', 'Age', 'City'] |
| 4 | Print first row | print(row) | row=['Name', 'Age', 'City'] | ['Name', 'Age', 'City'] |
| 5 | Read second row | for row in reader: | row=['Alice', '30', 'New York'] | ['Alice', '30', 'New York'] |
| 6 | Print second row | print(row) | row=['Alice', '30', 'New York'] | ['Alice', '30', 'New York'] |
| 7 | Read third row | for row in reader: | row=['Bob', '25', 'Los Angeles'] | ['Bob', '25', 'Los Angeles'] |
| 8 | Print third row | print(row) | row=['Bob', '25', 'Los Angeles'] | ['Bob', '25', 'Los Angeles'] |
| 9 | No more rows | for row in reader: | row=None | |
| 10 | Close file automatically | end of with block | file closed |
| Variable | Start | After Step 3 | After Step 5 | After Step 7 | Final |
|---|---|---|---|---|---|
| file | None | open | open | open | closed |
| reader | None | csv.reader object | csv.reader object | csv.reader object | csv.reader object |
| row | None | ['Name', 'Age', 'City'] | ['Alice', '30', 'New York'] | ['Bob', '25', 'Los Angeles'] | None |
Working with CSV files in Python: - Use 'import csv' to access CSV tools. - Open file with 'with open(filename) as file:' for safe handling. - Create a reader with 'csv.reader(file)'. - Loop over reader to get each row as a list. - File closes automatically after 'with' block ends.