Working with CSV Files
Chapter 13 · Tamil Nadu State Board
- 16 min read
- 5-question quiz
Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content
In short
This lesson teaches how CSV files store tabular data as text and how they differ from Excel files. It explains how to create CSV files, including how to handle commas, line breaks and double quotes inside fields. It also shows how Python can read, sort, modify and write CSV data using the csv module. These skills help students process table data and save it in a format that is easy to use across programs.
Written by AI from this lesson. How we check it
Key points
- CSV stores table-like data as text, with fields separated by commas or another delimiter.
From your textbook
“A CSV file is a human readable text file where each line has a number of fields, separated by commas or some other delimiter.”
- Unlike Excel files, CSV files are plain text and do not preserve formatting or formulas.
From your textbook
“CSV format is a plain text format with a series of values separated by commas.”
- Put double quotes around a field that contains a comma or a line break so it is treated as one field.
From your textbook
“Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.”
- When a field contains a double quote, double that quote inside the field.
From your textbook
“a double-quote appearing inside a field must be preceded with another double quote.”
- Python's csv module can read CSV data as rows or map its fields to dictionary keys.
From your textbook
“The two ways to read a CSV file are using csv.reader() function and using DictReader class.”
- Use append mode to add a row at the end of an existing CSV file; write mode can overwrite an existing file.
From your textbook
“‘a’ append mode add the data at the end of the file if the file already exists otherwise creates a new one”
CSV Files and Their Uses
Definition
- CSV file
- A CSV file is a plain text file that stores table data in rows, with values separated by commas or another delimiter.
Each line can be treated as a row, and each value as a column. CSV files are easy to read and move between different programs. Python's CSV module can read and write most CSV files.
What CSV files can and cannot do
- CSV files can store tabular data, such as spreadsheet or database data.
- They can be opened in text editors and spreadsheet programs.
- They do not store charts, graphs, formatting, formulas, or macros.
- A CSV file is also called a Flat File.
CSV and Excel file formats
| CSV | Excel |
|---|---|
| Plain text, usually with values separated by commas. | A binary file that can store worksheet content and formatting. |
| Can be opened with text editors and spreadsheet programs. | Files saved in Excel format cannot be opened or edited by text editors. |
| Importing can be faster and uses less memory. | Importing uses more memory. |
| Uses the .csv extension. | Uses its own formats, such as xls or xlsx. |
Remember: CSV stores table values as text; it does not preserve spreadsheet formatting or formulas.
Creating and Formatting CSV Data
You can create a CSV file in Notepad or another text editor. Put commas between values and start each new row on a new line. Save the file with the .csv extension.
Worked example
How can these rows be written as CSV data: Topic1, Topic2, Topic3; one, two, three; Example1, Example2, Example3?
Try it first, then show the solutionSolution
- Separate the values in each row with commas.
- Place each row on its own line.
Answer: Topic1,Topic2,Topic3 one,two,three Example1,Example2,Example3
A comma inside a value could be mistaken for a separator. Put a value containing a comma inside double quotes. Use the same method for a value that contains a newline.
Worked example
How should the address Mylapore, Chennai appear as one CSV field?
Try it first, then show the solutionSolution
- Enclose the whole address in double quotes.
Answer: "Mylapore, Chennai"
If a value contains double quotes, double each internal quote so it is read as part of the value. When quotes enclose a field, a double quote inside that field must be preceded by another double quote.
CSV formatting rules
- Put each record, or row, on a separate line.
- The last record may or may not end with a line break.
- A header line is optional. If used, it should have the same number of fields as the records.
- Separate fields with commas. Spaces are part of a field and should not be ignored.
- Do not put a comma after the last field in a record.
- Fields may be enclosed in double quotes. A field containing a comma, line break, or double quote should be enclosed in double quotes.
- Keep commas for empty fields so that fields stay in their correct columns.
Remember: Use double quotes around fields containing commas, line breaks, or double quotes, and double any quote inside a quoted field.
Saving a Spreadsheet as a CSV File
In Microsoft Excel, enter the data in a worksheet. Choose File → Save As, then select CSV (Comma delimited) as the save type, or give the file a .csv extension. You can open the saved file in a text editor to view or edit its contents.
Worked example
How can worksheet data be saved as a CSV file in Microsoft Excel?
Try it first, then show the solutionSolution
- Open the worksheet containing the data.
- Choose File → Save As.
- Select CSV (Comma delimited) as the save type, or use the .csv extension.
Answer: The worksheet is saved as a CSV file.
Opening CSV Files in Microsoft Excel
If Microsoft Excel is installed, double-clicking a CSV file usually opens it in Excel. If an Open With prompt appears, choose Microsoft Excel. You can also open Excel, choose File → Open, and select the CSV file.
If the file is not listed, change the file type to Text Files (*.prn, *.txt, *.csv). If both MS Excel and Open Office calc are installed, the CSV file opens in MS Excel by default.
Reading CSV Files with Python
Python’s CSV module provides tools to read, write, and process CSV data. CSV files are used extensively in e-commerce applications because they are easy to process.
Two ways to read a CSV file
- Use the csv module’s reader function.
- Use the DictReader class.
Steps for working with a file
- Open the file.
- Perform a read or write operation.
- Close the file to free the resources tied to it.
Python’s built-in open() function opens a file and returns a file object, also called a handle. You can give the filename or full path in single or double quotes. The default mode is 'r', or 'rt', which reads text as strings.
Python file modes
| Mode | Purpose |
|---|---|
| 'r' | Open a file for reading. This is the default. |
| 'w' | Open a file for writing. Create it if it does not exist; otherwise, truncate it. |
| 'x' | Open a file for exclusive creation. The operation fails if the file already exists. |
| 'a' | Append at the end without truncating. Create the file if it does not exist. |
| 't' | Open in text mode. This is the default. |
| 'b' | Open in binary mode. |
| '+' | Open for updating by reading and writing. |
Binary mode returns bytes and is used for non-text files such as image or exe files. Close a file with close() after using it. A with statement is safer because it closes the file when its block ends, even if an exception occurs.
Worked example
How can a file be opened for reading and writing in binary mode?
Try it first, then show the solutionSolution
- Use open() with the filename and mode 'r+b'.
- The file object can then be used for file operations.
Answer: f = open('image1.bmp','r+b')
Reading CSV Rows with csv.reader()
Definition
- csv.reader()
- A function that reads each line of a CSV file and makes a list of its columns.
The reader function can read CSV data using formats such as quotes, pipes, or commas. Its syntax is csv.reader(fileobject,delimiter,fmtparams). The file object gives the file and its mode; delimiter and fmtparams are optional.
Definition
- Dialect
- A set of CSV formatting parameters that can be created, stored, and reused when reading or writing data.
For a CSV file with commas, csv.reader() reads each row as a list. A dialect can change how the reader handles details such as spaces after delimiters. The skipinitialspace parameter removes those spaces when set to True; its default value is false.
Worked example
What rows are printed when sample1.csv contains the shown comma-separated data?
Try it first, then show the solutionSolution
- Open sample1.csv in read mode.
- Pass the file object to csv.reader().
- Print each row.
Answer: ['SNO', 'NAME', 'CITY'] ['12101', 'RAM', 'CHENNAI'] ['12102', 'LAVANYA', 'TIRUCHY'] ['12103', 'LAKSHMAN', 'MADURAI']
Worked example
How can spaces after commas be removed while reading sample2.csv?
Try it first, then show the solutionSolution
- Register a dialect with delimiter = ',' and skipinitialspace=True.
- Read the file using csv.reader() with that dialect.
Answer: The rows are printed without spaces at the start of each value: ['Topic1', 'Topic2', 'Topic3'], ['one', 'two', 'three'], and ['Example1', 'Example2', 'Example3'].
A dialect can also help read quoted values. For a file whose columns use the pipe symbol, register a dialect with delimiter = '|', then use that dialect with csv.reader().
Remember: Choose the delimiter and dialect to match the way the CSV file separates and formats its values.
Reading a Specific Column from a CSV File
Use csv.reader() to read rows from a CSV file. Each row is a list, so a column can be selected by its index. For example, col[0] selects the first column and col[3] selects the fourth column.
Example: print item names and profits
- Read each row from sample5.csv.
- Print col[0] and col[3] for each row.
Selected output from sample5.csv
| Item Name | Profit |
|---|---|
| Keyboard | 1152 |
| Monitor | 10400 |
| Mouse | 2000 |
Storing CSV Rows or Column Values in a List
Definition
- List
- A list is an ordered sequence of elements that can be changed, and list literals are written within square brackets [ ].
Start with an empty list using arrayValue = []. Use arrayValue.append(element) to add an element. To store all CSV rows, append each row while reading the file.
Storing a selected column for sorting
- Use next(reader) to skip the heading row.
- Ask the user for a column number between 0 to 3.
- Append that column's value from each remaining row to a list.
- Use arrayValue.sort(reverse=True) to arrange the values in descending order.
Worked example
Sort the values in column 2 of sample6.csv in descending order.
Try it first, then show the solutionSolution
- Skip the first row with next(reader).
- Select column number 2.
- Add each row's value from that column to arrayValue.
- Sort using arrayValue.sort(reverse=True).
Answer: 50, 12, 10
List sorting methods
| Command | Result |
|---|---|
| list_name.sort() | Arranges list values in ascending order. |
| list_name.sort(reverse=True) | Arranges list values in descending order. |
Sorting CSV Rows by a Column
To sort complete CSV rows by one column, read the rows into data and skip the heading with next(data). Use sorted() with operator.itemgetter(col_no) to choose the column used for sorting.
sortedlist = sorted(data, key=operator.itemgetter(1))
data is the rows to sort, and 1 selects the second column as the sorting key.
sorted() and sort()
| Method | What it does |
|---|---|
| sorted() | Returns the elements in a specified order. |
| sort() | Changes the original list and does not return a value. |
For sample8.csv, sorting by the second column gives Mouse with 20, Keyboard with 48, and Monitor with 52. To sort by more than one column, itemgetter can use multiple indices, such as operator.itemgetter(1,2). Use reverse=True to sort in descending order.
Reading a CSV File into a Dictionary
Definition
- DictReader
- DictReader reads CSV rows into dictionary-like objects, using the first row's comma-separated values as keys.
The column names become dictionary keys, and values from each later row are matched to those keys. If the first row does not contain column names, give fieldnames to the DictReader constructor to set the keys.
CSV reading and writing classes
| Classes | Data structure used |
|---|---|
| csv.reader() and csv.writer | List or tuple |
| csv.DictReader and csv.DictWriter | Dictionary |
Remember: Use DictReader when you want to access CSV values by column name instead of by list index.
Reading CSV Data into a Dictionary with a Custom Delimiter
A CSV file can use a separator other than a comma. Register a dialect with the required delimiter, then pass that dialect to csv.DictReader(). The example uses the vertical bar | as the delimiter.
How the example works
- csv.register_dialect() registers a dialect called myDialect with delimiter='|' and skipinitialspace=True.
- csv.DictReader() reads each row using the registered dialect.
- Each row is printed as dict(row).
Definition
- OrderedDict
- An OrderedDict is a dictionary subclass that saves the order in which its contents are added.
Remember: DictReader() gives an OrderedDict by default; use dict() to convert it to a normal dictionary.
Writing Rows to a CSV File
Definition
- csv.writer()
- csv.writer() returns a writer object that converts data into delimited strings for a file-like object.
The syntax is csv.writer(fileobject,delimiter,fmtparams). The fileobject identifies the file, while delimiter and fmtparams are optional settings. If no delimiter is given, the default separator is a comma (,).
Writing one row or many rows
| Method | Data it writes |
|---|---|
| writerow() | One row at a time; it takes 1-dimensional data. |
| writerows() | Multiple rows at once; it takes 2-dimensional data. |
In the Pupil.csv example, csv.writer() creates a writer for the file. writerows(csvData) writes all rows from the list, including the headings Student and Age and the pupil data.
Modifying and Appending CSV Rows
To modify a CSV file, read its rows with csv.reader() and store them in a list. Replace the required row, then write the list back with writerows(). In the example, lines[3] = row replaces the row with the new values for 3, Meena and Bangalore.
Definition
- Appending a row
- Appending a row means adding a new row at the end of an existing file.
Write mode and append mode
| Mode | What it does |
|---|---|
| 'w' | Creates a new file, or overwrites the file if it already exists. |
| 'a' | Adds data at the end of an existing file, or creates a new file if it does not exist. |
To append one row, open the CSV file in 'a' mode and use writerow(row). The example adds 6, Sajini and Madurai after the existing rows.
Remember: Choose 'a' to keep existing rows and add data at the end; 'w' overwrites an existing file.
Writing CSV Values with Quotes
A registered dialect can set how values are quoted. In the example, csv.register_dialect() registers myDialect with quoting=csv.QUOTE_ALL. The writer uses that dialect to put double quotes around every value.
Steps in the quoted CSV example
- Store the rows in the list info.
- Register myDialect with quoting=csv.QUOTE_ALL.
- Open person.csv in 'w' mode and create a writer using myDialect.
- Write each row with writer.writerow(row).
Remember: csv.QUOTE_ALL makes the writer put double quotes around all values.
Custom Delimiters and CSV Dialects
Definition
- Delimiter
- A delimiter is a string that separates fields in a CSV file.
The default delimiter is a comma. To use another delimiter, register a dialect with csv.register_dialect(). For example, a pipe (|) can separate fields instead.
Other dialect settings
- skipinitialspace=True ignores whitespace immediately after a delimiter. Its default value is False.
- A line terminator is a string that ends a line written by the writer. The listed default values are \r or \n.
- Python’s CSV module accepts \r\n, \n or \r as line terminators.
A dialect can also set a quote character and quoting style. In the example, the pipe separates fields, the double quote is the quote character, and csv.QUOTE_ALL puts quotes around every field.
Remember: Register a dialect when a CSV file needs custom delimiter, line terminator, or quote settings.
Writing Dictionaries to CSV Files
Definition
- DictWriter()
- DictWriter() creates a writer object that maps dictionary data to a CSV file using fieldnames as the column headings and dictionary keys.
Writing dictionary data
- Give the column headings through the fieldnames parameter.
- Use writeheader() to write the headings.
- Use writerows() to write the dictionary data.
A regular csv.writer() works with lists or tuples. csv.DictWriter() works with dictionaries. A custom dialect can also be passed to DictWriter() when the file needs settings such as a pipe delimiter.
CSV writing methods
| Method | What it writes |
|---|---|
| writerow() | One row at a time |
| writerows() | All the given rows at once |
| writeheader() | The fieldnames as column headings |
Remember: Use DictWriter() for dictionary data, and use fieldnames to set the headings and dictionary keys.
Collecting Data at Runtime and Writing CSV Files
A program can collect values through the keyboard and write them to a CSV file. In the example, it asks for a name, date of birth, and place, then writes those values as one row.
How the example works
- The program repeats while the answer is y.
- Each set of values is written with writerow().
- After input ends, the program opens the file for reading and prints each row.
The displayed reader output includes an empty list between data rows. The spreadsheet view shows the entered values arranged in columns.
Remember: writerow() writes one entered record as one CSV row.
CSV File Facts and Tools
A CSV file is a human-readable plain text file. Each line contains fields separated by commas or another delimiter. Excel is described as a binary file, while CSV is plain text.
Useful CSV facts
- csv.reader() and DictReader() are ways to read CSV data.
- csv.reader() and csv.writer() work with lists or tuples; csv.DictReader() and csv.DictWriter() work with dictionaries.
- CSV files use text mode by default for reading and writing. Binary mode is for non-text files such as image or exe files.
- close() frees resources tied to a file. Python’s garbage collector cleans up unreferenced objects.
- The CSV library contains code and objects for reading, writing, and processing CSV data.
- A CSV file with a custom delimiter is handled using csv.register_dialect().
- operator.itemgetter() with multiple indices can be used to sort by more than one column.
Remember: CSV stores readable text in rows, while its reader and writer tools can work with either row lists or dictionaries.
Questions students ask
Short, direct answers to what students search for in this chapter.
What is a CSV file?
A CSV file is a plain text file that stores table data. Each line represents a row, and commas or another delimiter separate the values. CSV files are easy to open in text editors and spreadsheet programs, but they do not store formatting, formulas, charts, or macros.
What is the difference between CSV and Excel files?
CSV is a plain text format with values separated by commas, while an Excel file is a binary file that can contain worksheet content and formatting. CSV files can be opened in text editors, and importing them can be faster and use less memory. Excel uses formats such as xls or xlsx.
How do I create a CSV file in Notepad?
Open a new file in Notepad. Separate values in each row with commas, and put each row on a new line. Save the file with the .csv extension. If a value contains a comma or newline, enclose that value in double quotes.
How do I save an Excel worksheet as a CSV file?
Open the worksheet in Microsoft Excel and choose File → Save As. Select CSV (Comma delimited) as the save type, or save the file with the .csv extension. The saved file can then be opened in a text editor to view or edit its contents.
How do you write commas and double quotes inside CSV fields?
Enclose a field containing a comma or a double quote in double quotes. If the field contains a double quote, double that internal quote so it is read as part of the value. Fields containing line breaks should also be enclosed in double quotes.
How do I open a CSV file in Microsoft Excel?
If Microsoft Excel is installed, double-click the CSV file. If an Open With prompt appears, choose Microsoft Excel. You can also open Excel, choose File → Open, and select the CSV file. If it is not listed, choose Text Files (*.prn, *.txt, *.csv) as the file type.
Show 17 more questions
What are the two ways to read a CSV file in Python?
Python provides two ways to read a CSV file: use the csv module’s reader function or use the DictReader class. The reader function reads each line and makes a list of the columns in that row.
What does skipinitialspace do in Python csv.reader?
The skipinitialspace parameter removes spaces after a delimiter when reading a CSV file. Register a dialect with skipinitialspace=True, then pass that dialect to csv.reader(). Its default value is false.
What is a dialect in Python CSV?
A dialect is a set of formatting parameters for reading and writing CSV data. It can define details such as the delimiter and how spaces after delimiters are handled. Dialects can be created, stored, and reused.
Why should I use the with statement to open a file in Python?
The with statement ensures that a file is closed when its block ends. This happens even if an exception occurs during a file operation. Closing the file frees the resources tied to it, so an explicit close() call is not needed inside the with block.
How do I read a specific column from a CSV file in Python?
Read the file with csv.reader() and loop through its rows. Each row is a list, so use the column's index to select a value. For example, col[0] selects the first column, while col[3] selects the fourth column.
How do I sort a selected CSV column in descending order?
Skip the heading row with next(reader), then collect the chosen column's values in a list. Sort the list with arrayValue.sort(reverse=True). This arranges the selected values in descending order.
How do I sort CSV rows by a particular column in Python?
Read the rows, skip the heading with next(data), and call sorted() with key=operator.itemgetter(col_no). The column number selects the sorting key. Use reverse=True in sorted() when you need descending order.
What is the difference between csv.reader() and csv.DictReader?
csv.reader() works with rows as lists or tuples. csv.DictReader reads rows into dictionary-like objects, using column names from the first row as keys. You can provide fieldnames when the first row does not contain column names.
How do I read a CSV file with a custom delimiter into a dictionary in Python?
Register a dialect with csv.register_dialect(), setting its delimiter to the separator used in the file. Pass the dialect name to csv.DictReader(). Each row is returned as an OrderedDict by default; use dict(row) to convert it to a normal dictionary.
What is the difference between writerow and writerows in Python CSV?
writerow() writes one row and takes 1-dimensional data. writerows() writes multiple rows and takes 2-dimensional data. For example, use writerows(csvData) when a list contains several rows to write at once.
What is the difference between w and a mode when writing a CSV file?
The 'w' mode creates a new file or overwrites an existing one. The 'a' mode adds data at the end of an existing file, or creates a new file if one does not exist. Use 'a' when you want to keep the existing rows.
How do I write every CSV value with double quotes in Python?
Register a dialect with quoting=csv.QUOTE_ALL, then create the writer using that dialect. Write rows with writer.writerow(). With this setting, the output puts double quotes around every value.
What is a delimiter in a CSV file?
A delimiter is a string that separates fields in a CSV file. A comma is the default delimiter. A different delimiter, such as a pipe (|), can be set by registering a dialect with csv.register_dialect().
How do I write a dictionary to a CSV file in Python?
Use csv.DictWriter() and give it fieldnames for the column headings and dictionary keys. Call writeheader() to write the headings, then use writerows() to write the dictionary data. A dialect can be supplied for custom CSV settings.
What is the difference between writerow and writerows?
writerow() writes one row at a time. writerows() writes all the given data rows at once. Both are used with a CSV writer to put data into a CSV file.
What does skipinitialspace do in a CSV dialect?
When skipinitialspace is True, whitespace immediately following a delimiter is ignored. Its default value is False.
How can a Python program write keyboard input to a CSV file?
Open a CSV file for writing and create a writer with csv.writer(). Ask the user for the needed values, then pass them as a list to writerow(). Repeat while the user chooses to enter more data.
Book back answers
19 textbook exercises, solved and checked against the book. Questions we could not prove are left out.
Choose the best answer (1 Mark)
A CSV file is also known as a ….
- (A) Flat File
- (B) 3D File
- (C) String File
- (D) Random File
Try it, then show the answerAnswer
(A) Flat File
The chapter states that a CSV file is also known as a Flat File.
From the book: “A CSV file is also known as a Flat File.”
Which of the following module is provided by Python to do several operations on the CSV files?
- (A) py
- (B) xls
- (C) csv
- (D) os
Try it, then show the answerAnswer
(C) csv
Python provides a module named CSV for operations on CSV files.
From the book: “Python provides a module named CSV, using this you can do several operations on the CSV files.”
Which of the following mode is used when dealing with non-text files like image or exe files?
- (A) Text mode
- (B) Binary mode
- (C) xls mode
- (D) csv mode
Try it, then show the answerAnswer
(B) Binary mode
Binary mode returns bytes and is used for non-text files such as image or exe files.
From the book: “this is the mode to be used when dealing with non-text files like image or exe files.”
The command used to skip a row in a CSV file is
- (A) next()
- (B) skip()
- (C) omit()
- (D) bounce()
Try it, then show the answerAnswer
(A) next()
The chapter's example skips the first row by calling next(reader).
From the book: “# skipping the first row(heading) next(reader)”
Practice
Why are CSV fields containing commas enclosed in double quotes?
Exam questions
Practice questions with model answers. These are not from an official paper.
How does CSV differ from an Excel file?2 marks
CSV is plain text with values separated by delimiters, while an Excel file is binary and can store worksheet content and formatting. CSV files are easier to open with text editors and generally use less memory when imported.
How should CSV fields containing commas or double quotes be formatted?2 marks
Enclose a field containing commas in double quotes so its commas are not treated as separators. If the field contains double quotes, double those internal quote marks.
Describe two ways to read CSV data in Python and how they represent the data.2 marks
Use csv.reader() to read rows as lists, or use DictReader to map the values in each row to dictionary keys, usually taken from the first row.
Explain the difference between write mode and append mode when opening a file.2 marks
Write mode creates a file or truncates it if it already exists. Append mode adds data at the end of an existing file, and creates the file if it does not exist.
Watch out
- Do not treat every comma in a CSV file as a field separator; commas inside quoted fields belong to the data.
- Do not confuse csv.reader() and DictReader: the first works with row lists, while the second maps values to dictionary keys.
Still stuck on this lesson?
Get an AI answer grounded in your actual textbook — with the exact page reference.
Ask AI about this topic →