6.4.2 CSV file handling
What Is a CSV File?
A CSV (Comma-Separated Values) file is a plain text file where each line represents one record and the fields within each record are separated by commas. CSV is a universal format for storing tabular data — it can be opened in spreadsheet applications and read by programs in any language.
Name,Age,Score
Alice,16,85
Bob,17,72
Carol,16,91
The first line is typically a header row naming the columns. Each subsequent line is a data record.
Reading a CSV File
# Reading a CSV file in Python
file = open("students.csv", "r")
header = file.readline() # read and discard the header row
for line in file:
line = line.strip() # remove trailing newline character
fields = line.split(",") # split on comma into a list
name = fields[0]
age = int(fields[1]) # convert to correct type
score = int(fields[2])
print(name, "| Age:", age, "| Score:", score)
file.close() # always close the file when done
.strip() removes the invisible
newline at the end of each line. Without it, the last field of every record contains a trailing newline character.
// Reading a CSV file in C#
using System.IO;
string[] lines = File.ReadAllLines("students.csv");
// lines[0] is the header — start from index 1
for (int i = 1; i < lines.Length; i++) {
string[] fields = lines[i].Split(',');
string name = fields[0];
int age = int.Parse(fields[1]);
int score = int.Parse(fields[2]);
Console.WriteLine(name + " | Age: " + age + " | Score: " + score);
}
' Reading a CSV file in VB.NET
Imports System.IO
Dim lines() As String = File.ReadAllLines("students.csv")
' lines(0) is the header — start from index 1
For i As Integer = 1 To lines.Length - 1
Dim fields() As String = lines(i).Split(","c)
Dim name As String = fields(0)
Dim age As Integer = Integer.Parse(fields(1))
Dim score As Integer = Integer.Parse(fields(2))
Console.WriteLine(name & " | Age: " & age & " | Score: " & score)
Next
Writing a CSV File
# Writing a CSV file in Python
file = open("results.csv", "w")
file.write("Name,Score,Grade
") # write header row
students = [["Alice", 85, "A"],
["Bob", 72, "B"],
["Carol", 91, "A"]]
for student in students:
line = student[0] + "," + str(student[1]) + "," + student[2] + "
"
file.write(line)
file.close()
print("File written successfully.")
Opening with "w" creates a new file (or overwrites an existing one). To add to an existing file without overwriting, use "a" (append mode).
using System.IO;
string[][] students = {
new[] {"Alice", "85", "A"},
new[] {"Bob", "72", "B"},
new[] {"Carol", "91", "A"}
};
using (StreamWriter sw = new StreamWriter("results.csv")) {
sw.WriteLine("Name,Score,Grade");
foreach (string[] s in students)
sw.WriteLine(string.Join(",", s));
}
Console.WriteLine("File written.");
Imports System.IO
Dim students()() As String = {
New String() {"Alice", "85", "A"},
New String() {"Bob", "72", "B"},
New String() {"Carol", "91", "A"}
}
Using sw As New StreamWriter("results.csv")
sw.WriteLine("Name,Score,Grade")
For Each s() As String In students
sw.WriteLine(String.Join(",", s))
Next
End Using
Console.WriteLine("File written.")
Key Takeaways
- CSV files store tabular data as plain text: one record per line, fields separated by commas.
- Reading: open file → read lines →
.strip()newlines →.split(",")to get fields → convert types. - Writing: open file with
"w"→ write header → write each record as a comma-separated string followed by→ close. - Always call
file.close()— or use awithstatement — to ensure the file is properly saved and resources are released. .strip()is essential when reading — it removes the invisible newline character from the end of each line.