Get the most accurate TN Board Solutions for Class 12 Computer Science Chapter 13 Python and CSV Files here. Updated for the 2026-27 academic session, these solutions are based on the latest TN Board textbooks for Class 12 Computer Science. Our expert-created answers for Class 12 Computer Science are available for free download in PDF format.
Detailed Chapter 13 Python and CSV Files TN Board Solutions for Class 12 Computer Science
For Class 12 students, solving TN Board textbook questions is the most effective way to build a strong conceptual foundation. Our Class 12 Computer Science solutions follow a detailed, step-by-step approach to ensure you understand the logic behind every answer. Practicing these Chapter 13 Python and CSV Files solutions will improve your exam performance.
Class 12 Computer Science Chapter 13 Python and CSV Files TN Board Solutions PDF
I. Choose the Best Answer (1 Mark)
Question 1. A CSV file is also known as a........................ (March 2020)
(a) Flat File
(b) Object File
(c) String File
(d) Random File
Answer: (a) Flat File
In simple words: A CSV file is a simple type of data file that stores information in a plain text format, similar to a flat file. This means it does not have special structures like databases or spreadsheets.
π― Exam Tip: Remember that "Flat File" refers to a file where all data is stored in a single table, making CSV a perfect example of this structure.
Question 2. The expansion of CRLF is
(a) Control Return and Line Feed
(b) Carriage Return and Form Feed
(c) Control Router and Line Feed
(d) Carriage Return and Line Feed
Answer: (d) Carriage Return and Line Feed
In simple words: CRLF is a special sequence of characters used in computer files to show where a new line starts. It combines two actions: moving the cursor to the beginning of the line (Carriage Return) and then moving it down to the next line (Line Feed).
π― Exam Tip: CRLF is important for text files because it tells programs how to correctly display text on different lines, especially when files are moved between operating systems like Windows and Unix.
Question 3. 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
Answer: (c) csv
In simple words: Python has a special tool, or module, named `csv` that helps you work with CSV files easily. This module provides functions to read from and write to CSV files without needing to handle all the tricky formatting details yourself.
π― Exam Tip: Always import the `csv` module at the beginning of your Python script when you plan to work with CSV files, using `import csv`.
Question 4. 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
Answer: (b) Binary mode
In simple words: When you open files like pictures or programs, you use "binary mode" because these files contain raw data, not simple text characters. This mode handles the file content as a stream of bytes, which is exactly how non-text files are stored.
π― Exam Tip: For binary files, always include 'b' in the file mode, such as 'rb' for reading binary or 'wb' for writing binary, to prevent data corruption.
Question 5. The command used to skip a row in a CSV file is
(a) next()
(b) skip()
(c) omit()
(d) bounce()
Answer: (a) next()
In simple words: In Python, when you are reading a CSV file row by row, the `next()` function is used to move past the current row and get to the next one. This is often useful for skipping header rows.
π― Exam Tip: The `next()` function can be called on an iterator, like the one returned by `csv.reader()`, to advance the position and get the next item.
Question 6. Which of the following is a string used to terminate lines produced by writer() method of csv module?
(a) Line Terminator
(b) Enter key
(c) Form feed
(d) Data Terminator
Answer: (a) Line Terminator
In simple words: A "line terminator" is a special character or set of characters that tells a program where one line of text ends and the next one begins. In CSV files, this helps organize each row of data.
π― Exam Tip: Common line terminators include `\n` (newline) and `\r\n` (carriage return followed by newline), which signify the end of a record in a text file.
Question 7. What is the output of the following program?
import csv
with open('city.csv', 'r') as d:
reader = csv.reader(d)
next(d)
for row in d:
print(row)
if the file called "city.csv" contain the following details
chennai,mylapore
mumbai,andheri
(a) chennai,mylapore
(b) mumbai,andheri
(c) chennai,mumbai
(d) chennai,mylapore
Answer: (b) mumbai,andheri
In simple words: The program first skips the very first line of the file, which is "chennai,mylapore". Then, it prints the next line, which is "mumbai,andheri".
π― Exam Tip: Pay close attention to the `next(d)` line; it advances the file pointer, effectively skipping the first row when iterating through the file.
Question 8. Which of the following creates an object which maps data to a dictionary?
(a) listreader()
(b) reader()
(c) tuplereader()
(d) DicReader ()
Answer: (d) DicReader ()
In simple words: The `csv.DictReader` class in Python's `csv` module is designed to read data from a CSV file and turn each row into a dictionary. This makes it easier to access data using column names as keys.
π― Exam Tip: `DictReader` is very useful when dealing with CSV files that have a clear header row, as it uses these headers as keys for the dictionary.
Question 9. Making some changes in the data of the existing file or adding more data is called
(a) Editing
(b) Appending
(c) Modification
(d) Deleting
Answer: (c) Modification
In simple words: When you change existing data in a file or add new data to it, this overall action is called modification. It's a general term for updating the file's content.
π― Exam Tip: "Modification" is a broader term that includes both editing (changing existing content) and appending (adding new content to the end) of a file.
Question 10. What will be written inside the file test, csv using the following program
import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')
with open('c:\pyprg\chl3\line2.csv', 'w') as f:
wr = csv.writer(f,dialect='M')
wr.writerows(D)
f.close()
(a) Exam Quarterly Halfyearly
(b) Exam Quarterly Halfyearly
(c) EQH
(d) Exam, Quarterly, Halfyearly
Answer: (d) Exam, Quarterly, Halfyearly
In simple words: The program writes each item from the list `D` into the CSV file, with each item on a new line because of the `\n` line terminator. So, "Exam", "Quarterly", and "Halfyearly" will each be on their own line in the file.
π― Exam Tip: The `writerows()` method writes multiple rows at once. Each sub-list in `D` represents a row, and the `lineterminator` ensures they are correctly separated.
II. Answer the Following Questions (2 Marks)
Question 1. What is CSV File?
Answer: A CSV file is a text file that humans can easily read. In this file, each line has several data fields that are separated by commas or other characters. CSV stands for Comma Separated Values. A CSV file is also known as a Flat File because it stores data in a simple table structure. You can import and export files in CSV format using many programs, like Microsoft Excel or OpenOffice Calc. This makes CSV a very versatile format for data exchange.
π― Exam Tip: When defining a CSV file, always mention that it's a "human-readable text file" and that fields are "separated by commas or other delimiters."
Question 2. Mention the two ways to read a CSV file using Python.
Answer: There are two main ways to read a CSV file using Python's built-in `csv` module:
1. **Using the `csv.reader()` function:** This function reads each line of the CSV file as a list of strings. It is suitable for simple CSV files where you just need to process data sequentially.
2. **Using the `csv.DictReader` class:** This class reads each line of the CSV file as a dictionary. It uses the first row of the file as keys for the dictionary, making it easier to access data by column name. This is often preferred for files with clear headers.
Both methods help you manage data from CSV files efficiently.
π― Exam Tip: Clearly distinguish between `csv.reader()` (returns lists) and `csv.DictReader` (returns dictionaries) in your answer.
Question 3. Mention the default modes of the File.
Answer: By default, files are opened in text mode for reading. This means that when data is read from the file, it is treated as strings of characters. The default mode for CSV files, whether for reading or writing, is also text mode. Text mode is suitable for handling data that is character-based. The table below outlines common file modes:
| Mode | Description |
|---|---|
| 'r' | Opens a file for reading (default). |
| 't' | Opens in text mode (default). |
In simple words: When you open a file, it usually opens in "text mode" and is ready for "reading". This means the computer sees the file's content as normal letters and numbers.
π― Exam Tip: Remember that 'r' is for read mode and 't' is for text mode, and both are default when not specified. The 't' mode ensures proper handling of character encodings.
Question 4. What is the use of next() function?
Answer: The `next()` function in Python is primarily used to retrieve the next item from an iterator. When working with CSV files, it is commonly used to skip the header row of a file. For example, if a CSV file has column names in the first row, calling `next(reader_object)` will advance the reader past that header, allowing you to process only the actual data rows. This ensures that calculations or data processing do not mistakenly include the header labels.
**Example:**
`sortedlist = sorted(data, key=operator.itemgetter(1))`
This example shows how `itemgetter(1)` can be used with `sorted` for sorting, implying `next()` can be useful to skip headers before such operations.
In simple words: The `next()` function helps you get the next piece of data from a list or a file reader. In CSV files, it's often used to jump over the very first line which usually contains the column names.
π― Exam Tip: The `next()` function is crucial for efficiently handling CSV files that have a header row, as it prevents the header from being processed as data.
Question 5. How will you sort more than one column from a csv file? Give an example
Answer: To sort a CSV file by more than one column, you can use the `operator.itemgetter()` function along with `sorted()`. The `itemgetter()` function allows you to specify multiple indices (column numbers) for sorting. The `sorted()` function then uses these indices to sort the data. You can also specify `reverse=True` if you want to sort in descending order.
**Syntax:**
`sortedlist = sorted(data, key=operator.itemgetter(Colnumber1, Colnumber2), reverse=True)`
**Example:**
`import csv`
`import operator`
`data = csv.reader(open('c:\\PYPRG\\sample8.csv'))`
`next(data) # To omit the header row`
`# Using operator module for sorting multiple columns`
`sortedlist = sorted(data, key=operator.itemgetter(1,2))`
In this example, the data is first read from 'sample8.csv', the header is skipped, and then the data is sorted based on the second and third columns (indices 1 and 2). This allows for complex sorting requirements.
In simple words: To sort a CSV file by many columns, you can tell Python to look at multiple columns at once using `itemgetter`. Python will then arrange the rows based on the first chosen column, and if there are ties, it will use the second chosen column, and so on.
π― Exam Tip: When using `operator.itemgetter()`, remember that column indices start from 0. For multi-column sorting, list the column indices in the order of sorting priority.
III. Answer the Following Questions (3 Marks)
Question 1. Write a note on open() function of python. What is the difference between the two methods?
Answer: Python provides a built-in `open()` function to open files. This function creates a file object, also known as a handle, which programs use to read from or modify the file.
**For example:**
`>>> f = open('sample.txt', 'r')` Opens `sample.txt` in the current directory for reading. `f` is the file object.
`>>> f = open('c:\\pyprg\\chl3sample5.csv', 'r')` Specifies the full path to a file for reading.
You can specify different modes when opening a file, such as 'r' for reading, 'w' for writing, or 'a' for appending. You can also specify whether the file should be opened in "text mode" or "binary mode".
By default, files are opened in text mode. In this mode, any data read from the file is treated as strings of characters. Binary mode returns bytes instead of characters, and this mode is used for non-text files like images or executable files.
The typical way to open and close a file looks like this:
`f = open("test.txt") # Default mode is text mode ('rt')`
`# Perform file operations`
`f.close()`
However, this method is not entirely safe because if an error happens while performing file operations, the program might exit without closing the file. The best and safest way to handle file operations is using the `with` statement. This ensures that the file is automatically closed once the code block within `with` is exited, even if errors occur. You don't need to explicitly call the `close()` method when using `with`.
In simple words: Python's `open()` function helps you get access to a file. You can choose how to open it: to read, write, or add more data, and whether it's a simple text file or a binary file like a picture. Using `with open()` is the safest way to ensure the file is always closed properly, even if something goes wrong.
π― Exam Tip: Emphasize the safety and convenience of using `with open(...) as file_object:` over manually calling `open()` and `close()`, especially regarding error handling.
Question 2. Write a Python program to modify an existing file.
Answer: Here is a Python program that modifies an existing CSV file by replacing a specific row and then displaying the original and modified file contents.
**Coding:**
`import csv`
`row = ['3', 'Meena', 'Bangalore']`
`# Read the original file`
`with open('student.csv', 'r') as readFile:`
` reader = csv.reader(readFile)`
` lines = list(reader) # Store all rows in a list`
` lines[3] = row # Replace the 4th row (index 3) with the new row`
`# Write the modified content back to the file`
`with open('student.csv', 'w') as writeFile:`
` writer = csv.writer(writeFile)`
` writer.writerows(lines)`
`readFile.close()`
`writeFile.close()`
**Original File (`student.csv`):**
| Roll No | Name | City |
|---|---|---|
| 1 | Harshini, | Chennai |
| 2 | Adhith, | Mumbai |
| 3 | Dhuruv | Bangalore |
| 4 | egiste, | Tirchy |
| 5 | Venkat | Madurai |
**Modified File after the coding:**
| Roll No | Name | City |
|---|---|---|
| 1 | Harshini, | Chennai |
| 2 | Adhith, | Mumbai |
| 3 | Meena | Bangalore |
| 4 | egiste, | Tirchy |
| 5 | Venkat | Madurai |
In simple words: This program first reads all the lines from the `student.csv` file. Then, it changes one specific line (the third student's record) with new information. Finally, it writes all the lines, including the changed one, back into the same `student.csv` file, updating it.
π― Exam Tip: When modifying a file, it's often easiest to read all content into memory, make changes, and then write the entire modified content back to the file. Remember to close file objects after use.
Question 3. Write a Python program to read a CSV file with default delimiter comma (,).
Answer: This Python program demonstrates how to read a CSV file where values are separated by the default delimiter, a comma.
**Coding:**
`# Importing the csv module`
`import csv`
`# Opening the csv file (sample1-csv) located at a different path in read mode`
`with open('c:\\pyprg\\sample1-csv', 'r') as F:`
` reader = csv.reader(F)`
` # Printing each line of data row by row`
` for row in reader:`
` print(row)`
`# The file is automatically closed by the 'with' statement`
**Output:**
`['SNO', 'NAME', 'CITY']`
`['12101', 'RAM', 'CHENNAI']`
`['12102', 'LAVANYA', 'TIRCHY']`
`['12103', 'LAKSHMAN', 'MADURAI']`
This program first imports the `csv` module. It then opens 'sample1-csv' in read mode. The `csv.reader()` function is used to create an iterator that processes each line, treating commas as separators by default. Finally, each row is printed as a list of strings, showing the contents of the CSV file.
In simple words: This program reads a CSV file line by line. It uses a special tool called `csv.reader` to understand that commas separate different pieces of information in each line. Then, it prints out each line as a list of items.
π― Exam Tip: For basic CSV reading, `csv.reader()` is sufficient, and Python automatically assumes comma (`,`) as the delimiter if not specified.
Question 4. What is the difference between the write mode and append mode?
Answer: The `write` mode ('w') and `append` mode ('a') are two different ways to open a file for writing, each with distinct behavior.
| Write Mode ('w') | Append Mode ('a') |
|---|---|
| The write mode creates a new file. | Append mode is used to add data at the end of the file if the file already exists. |
| If the file already exists, write mode overwrites it, erasing all previous content. | If the file already exists, append mode adds new content to the end without deleting existing data. |
| If the file does not exist, it creates a new one. | If the file does not exist, it also creates a new one. |
In simple words: Think of `write` mode as starting with a blank page; it will erase everything if the file already exists. `Append` mode is like adding more notes to the end of a page; it keeps the old notes and just adds new ones.
π― Exam Tip: Always be cautious when using 'w' mode, as it can lead to accidental data loss if you overwrite an important file. Use 'a' mode when you only want to add new data.
Question 5. What is the difference between reader() and DictReader() function?
Answer: The `csv.reader()` and `csv.DictReader()` functions in Python's `csv` module both read CSV files, but they structure the output data differently.
| reader() | DictReader() function |
|---|---|
| `csv.reader` and `csv.writer` work with lists or tuples, treating each row as a sequence of values. | `csv.DictReader` and `csv.DictWriter` work with dictionaries, mapping data to key-value pairs. |
| `csv.reader` and `csv.writer` do not take additional arguments for field names directly; they process fields by their order. | `csv.DictReader` and `csv.DictWriter` can take an `fieldnames` argument, which specifies the dictionary keys to be used. These keys are usually taken from the first row of the CSV. |
In simple words: `reader()` gives you each row as a simple list of items, while `DictReader()` gives you each row as a dictionary. In `DictReader()`, the names from the top row of your CSV file become the labels (keys) for each piece of data, making it easier to find specific information.
π― Exam Tip: Use `csv.reader()` when column order is important or headers are absent/irrelevant. Use `csv.DictReader` when column names are known and provide more readable code.
IV. Answer the Following Questions (5 Marks)
Question 1. Differentiate Excel file and CSV file.
Answer: Excel files (like .xls or .xlsx) and CSV files (.csv) are both used for storing tabular data, but they have key differences in their format, functionality, and use cases.
| Excel | CSV |
|---|---|
| Excel is a binary file that holds information about all the worksheets in a file, including both content and formatting. | CSV format is a plain text format with a series of values separated by commas. It stores only raw data. |
| XLS files can only be read by applications that have been specially written to read their format, and can only be written in the same way. | CSV can be opened with any text editor in Windows like Notepad, MS Excel, Open Office, etc. It's universally compatible. |
| Excel is a spreadsheet that saves files into its own proprietary format, such as .xls or .xlsx. These formats are complex and include rich features. | CSV is a format for saving tabular information into a delimited text file with the extension .csv. It is a simple, standardized format. |
| Excel consumes more memory while importing data due to its extensive features and binary nature. | Importing CSV files can be much faster, and it also consumes less memory, making it efficient for large datasets. |
In simple words: Excel files are like fancy digital notebooks that can save many pages, colors, and calculations, but only specific programs can open them. CSV files are like simple plain text lists that only store words and numbers separated by commas, making them easy to open anywhere.
π― Exam Tip: Highlight that Excel files are complex, proprietary binary files with formatting, while CSV files are simple, open-standard plain text files without formatting. This is the core distinction.
Question 2. Tabulate the different modes with its meaning.
Answer: When working with files in Python, different modes specify how the file should be opened and what operations (reading, writing, appending) can be performed. Each mode has a specific meaning and impact on the file's content.
| Mode | Description |
|---|---|
| 'r' | Open a file for reading (default). The file pointer is placed at the beginning of the file. |
| 'w' | Open a file for writing. This mode creates a new file if it does not exist. If the file already exists, it truncates (clears) the file, deleting all its previous content. |
| 'x' | Open a file for exclusive creation. This means the operation fails if the file already exists, preventing accidental overwriting. |
| 'a' | Open for appending at the end of the file without truncating it. This mode creates a new file if it does not exist, and if it does exist, new data is written to the end. |
| 't' | Open in text mode (default). This mode processes files as text, handling character encoding. |
| 'b' | Open in binary mode. This mode processes files as raw bytes and is used for non-text files like images or executables. |
| '+' | Open a file for updating (reading and writing). This mode can be combined with other modes, e.g., 'r+' for reading and writing, 'w+' for writing and reading (truncates first). |
In simple words: File modes tell the computer how you want to open a file. 'r' is for reading, 'w' is for writing (and clearing existing content), 'a' is for adding to the end, 'x' is for creating a new file only, 't' is for text, 'b' is for raw binary data, and '+' lets you do both reading and writing.
π― Exam Tip: Memorize the primary modes ('r', 'w', 'a') and their effects on existing files (read-only, overwrite, append). Also, understand the 'b' and 't' modifiers for binary and text handling.
Question 3. Write the different methods to read a File in Python.
Answer: There are primarily two ways to read a CSV file in Python, each using a different method from the `csv` module:
1. **Using the `csv.reader()` function**
* This method allows you to read the contents of a CSV file as an iterable object, where each row is returned as a list of strings.
* The `reader()` function is designed to take each line of the file and convert it into a list, representing all columns in that row.
* Using this method, you can read data from CSV files that use various delimiters and quoting styles, like double quotes (`"`), pipes (`|`), or the default comma (`,`).
**Syntax for `csv.reader()`:**
`csv.reader(fileobject, delimiter, fmtparams)`
Where:
* `fileobject`: This passes the path and the mode of the file (e.g., `'r'` for read mode).
* `delimiter`: An optional parameter that specifies the character used to separate fields (e.g., `,`, `|`). If omitted, it defaults to a comma.
* `fmtparams`: An optional parameter that helps override the default settings for specific CSV formats, such as `skipinitialspace` (to remove whitespace after the delimiter) or `quoting` (to control how quotes are handled).
**Program Example:**
`import csv`
`with open('c:\\pyprg\\sample1-csv', 'r') as F:`
` reader = csv.reader(F)`
` for row in reader:`
` print(row)`
**Output:**
`['SNO', 'NAME', 'CITY']`
`['12101', 'RAM', 'CHENNAI']`
`['12102', 'LAVANYA', 'TIRCHY']`
`['12103', 'LAKSHMAN', 'MADURAI']`
2. **Using the `csv.DictReader` class**
* To read a CSV file into a dictionary, you use the `DictReader` class from the `csv` module. This class works similarly to `csv.reader()` but creates an object that maps data to a dictionary for each row.
* The keys for this dictionary are usually provided by the field names, which are typically taken from the first line of the CSV file. Each comma-separated value in this header line becomes a dictionary key.
* The values in subsequent rows then behave like dictionary values, accessible using the appropriate key (i.e., the fieldname). This makes data access more intuitive and robust.
**Program Example:**
`import csv`
`filename = 'c:\\pyprg\\sample8.csv'`
`with open(filename, 'r') as infile:`
` inputfile = csv.DictReader(infile)`
` for row in inputfile:`
` print(dict(row)) # dict() to print data as a dictionary`
**Output:**
`{'ItemName': 'Keyboard ', 'Quantity': '48'}`
`{'ItemName': 'Monitor', 'Quantity': '52'}`
`{'ItemName': 'Mouse ', 'Quantity': '20'}`
In simple words: Python gives you two main ways to read CSV files: `csv.reader` which turns each line into a list of words, and `csv.DictReader` which turns each line into a mini-dictionary where you can find information using column names like "ItemName" instead of just numbers. Both methods help you get data from CSV files.
π― Exam Tip: When discussing reading methods, remember to explain both `csv.reader()` (list-based) and `csv.DictReader` (dictionary-based), along with their respective syntax and advantages, especially for files with headers.
Question 4. Write a Python program to write a CSV File with custom quotes.
Answer: To write a CSV file with custom quotes, we need to import the `csv` module and define a custom dialect. This dialect specifies the delimiter, quote character, and quoting style. We then open a file in write mode using this dialect and use a `csv.writer` object to write the data. The `csv.QUOTE_ALL` setting makes sure all fields are enclosed in quotes, which is useful for data that might contain special characters.
Coding:import csv
csvData = [['SNO','Items'], ['l'/Pen'],
['2','Book'], ['3','Pencil']]
csv.register_dialect ('myDialect', delimiter = ' | ',quotechar = quoting = csv.QUOTE_ALL)
with open('c:\\pyprg\\ch13\\ quote. csv', 'w') as csvFile:
writer = csv.writer(csvFile, dialect='myDialect')
writer.writerows(csvData)
print ("writing completed")
When you open the "quote.csv" file in notepad, you will get the following output:
| Sl.No | "Items" |
|---|---|
| 1 | "Pen" |
| 2 | "Book" |
| 3 | "Pencil" |
π― Exam Tip: When writing CSV files, always ensure that your dialect settings match the requirements of the program or system that will read the file to avoid parsing errors. Using custom dialects helps manage complex data fields.
Question 5. Write the rules to be followed to format the data in a CSV file.
Answer: Here are the important rules for formatting data in a CSV file:
1. Each record, which is a row of data, should be on its own line. You separate lines by pressing the Enter key to create a line break. For example, `xxx,yyy`. This means each row of information gets its own separate line in the file.
2. The very last record in the file might or might not have a line break at the end. This means it's okay if the final line doesn't end with an explicit 'Enter' key press. For example, `ppp,qqq` followed by `yyy,xxx`.
3. A CSV file can have an optional header line at the very beginning. If present, this header line must follow the same format as the regular data lines. The header should contain names for each field and have the same number of fields as the other records.
4. Inside the header and each record, fields are separated by commas. Any spaces around the fields are considered part of the field data and should not be ignored. The very last field in a record should not have a comma after it. For example: `Red, Blue`.
5. Each field may or may not be enclosed in double quotes. If fields are not enclosed in double quotes, then double quotes should not appear inside the fields themselves. For example: `"Red","Blue","Green"` means field data with quotes. `Black,White,Yellow` means field data without quotes.
6. If a field contains special characters like line breaks (CRLF), double quotes, or commas, the entire field should be enclosed in double-quotes. This helps the reader know that these special characters are part of the data, not separators. For example: `Red, Blue, Green`.
7. If double-quotes are used to enclose a field, and the field itself contains a double-quote, that inner double-quote must be preceded by another double-quote (i.e., escaped). For example: `"Red,""Blue"",""Green"` shows how to handle a quote inside a quoted field.In simple words: CSV files follow simple rules. Each data row is a new line. You can have a header line. Fields in a row are separated by commas. If your data has commas or new lines, put the whole field in quotes. If a field in quotes has a quote inside, use two quotes for it.
π― Exam Tip: Remember that consistent use of delimiters and quoting rules is crucial for CSV files to be correctly parsed by different applications.
12th Computer Science Guide Python And CSV Files Additional Questions And Answers
I. Choose The Best Answer (1 Marks)
Question 1. CSV means files
(a) common server values
(b) comma-separated values
(c) correct separator values
(d) constructor separated value
Answer: (b) comma-separated values
In simple words: CSV stands for "Comma Separated Values." It means that information in the file is kept separate by commas.
π― Exam Tip: Knowing common abbreviations like CSV is important in computer science as they represent fundamental file formats or concepts.
Question 2. Abbreviation of CSV
(a) Condition systematic values
(b) Column separated values
(c) Comma solution values
(d) Comma-separated values
Answer: (d) Comma-separated values
In simple words: CSV is short for "Comma-Separated Values," meaning data items are separated by commas.
π― Exam Tip: Even though the previous question asked what CSV means, this question tests your understanding of the full abbreviation, so be precise with the wording.
Question 3. CSV files cannot be opened with
(a) notepad
(b) MS Excel
(c) open office
(d) HTML
Answer: (d) HTML
In simple words: You cannot open a CSV file directly with an HTML editor because HTML is for making web pages, not for editing plain text data.
π― Exam Tip: Understand that CSV files are plain text with a specific structure, making them compatible with text editors and spreadsheet programs, but not markup languages like HTML.
Question 4. Which of the following can protect if the data itself contains commas in a CSV file?
(a) ;
(b) ,
(c) " "
(d) '
Answer: (c) " "
In simple words: If some information in your CSV file has a comma inside it, you should put double quotes around that whole piece of information. This tells the computer that the comma is part of the data and not a separator between two different pieces of information.
π― Exam Tip: Enclosing data fields in double quotes is a standard CSV convention to handle delimiters and special characters within the data itself.
Question 5. In a CSV file, each record is to be located on a separate line, delimited by a line break by pressing
(a) Enter key
(b) ESV key
(c) Tab key
(d) Shift key
Answer: (a) Enter key
In simple words: Each row of information in a CSV file starts on a new line, just like when you press the 'Enter' key to start a new line of text.
π― Exam Tip: Understanding that line breaks define record boundaries is fundamental to correctly parsing CSV file content.
Question 6. Find the wrong statement.
(a) CSV files can be opened with any text editor
(b) Excel files can be opened with any text editor
Answer: (b) Excel files can be opened with any text editor
In simple words: This statement is wrong because Excel files are not plain text files; they are binary files and can only be opened by specific spreadsheet programs, not just any text editor. CSV files, however, are plain text.
π― Exam Tip: Remember the key difference: CSV files are plain text (human-readable), while Excel files are proprietary binary files (machine-readable by specific software).
Question 7. built-in function is used to open a file in Python.
(a) readfn ()
(b) open ()
(c) reader ()
Answer: (b) open ()
In simple words: In Python, the `open()` function is the basic command you use to start working with any file, whether you want to read from it or write to it.
π― Exam Tip: The `open()` function is fundamental for file handling in Python; always remember its purpose and basic usage.
Question 8. mode can be used when CSV files dealing with non-text files.
(a) Write mode
(b) Binary mode
(c) Octal mode
(d) Write mode
Answer: (b) Binary mode
In simple words: When you work with files that are not just plain text, like images or programs, you need to open them in 'binary mode'. This tells the computer to read them as raw bytes, not as readable text.
π― Exam Tip: Distinguish between text mode (for readable characters) and binary mode (for raw bytes) when handling different file types in programming.
Question 9. The default file open mode is
(a) rt
(b) x
(c) a
(d) rw
Answer: (a) rt
In simple words: If you don't specify how to open a file, Python will open it in 'read text' mode by default. This means it expects to read text from the file.
π― Exam Tip: Always be aware of the default file mode (`'rt'`) to prevent unexpected behavior when opening files without explicitly stating the mode.
Question 10. Any field containing a newline as part of its data should be given in
(a) quotes
(b) double-colon
(c) colon
(d) double quotes
Answer: (d) double quotes
In simple words: If a piece of data in your CSV file has a new line inside it, you must put double quotes around that entire piece of data. This tells the program reading the file that the new line is part of the data itself, not the end of a record.
π― Exam Tip: Fields with embedded newlines, commas, or double quotes must always be enclosed in double quotes for correct parsing in CSV files.
Question 11. function is designed to take each line of the file and make a list of all columns?
(a) read ()
(b) reader ()
(c) row ()
(d) list ()
Answer: (b) reader ()
In simple words: The `reader()` function from the CSV module helps you read a CSV file line by line. Each line it reads is turned into a list, where each item in the list is a column from that line.
π― Exam Tip: The `csv.reader()` function is essential for iterating over lines in CSV files and accessing individual fields as a list.
Question 12. describes the format of the CSV file that is to be read.
(a) line space
(b) dialect
(c) whitespace
(d) delimiter
Answer: (b) dialect
In simple words: A 'dialect' in the CSV module describes all the specific rules for how a CSV file is set up, like what separates the values, how quotes are used, and how new lines are handled.
π― Exam Tip: Understanding CSV 'dialects' is key to correctly handling different CSV file variations, as it defines the precise formatting rules.
Question 13. Find the correct statement
(I) The last record in the file may or may not have an ending line break
(II) Header is a must with the same format as record lines.
(a) (I) is true, (II) is False
(b) (I) is False, (II) - True
(c) (I), (II) - both are true
Answer: (a) (I) is true, (II) is False
In simple words: Statement (I) is true because a CSV file's last line doesn't always need a line break. Statement (II) is false because a header in a CSV file is optional, not a must.
π― Exam Tip: Remember that while headers are good practice, they are not mandatory in CSV files, and the presence of a final line break is flexible.
Question 14. is used to add elements in CSV.
(a) update ()
(b) write ()
(c) append ()
(d) addition ()
Answer: (c) append ()
In simple words: To add new information to an existing CSV file without deleting the old content, you use the 'append' mode. This adds new data to the end of the file.
π― Exam Tip: Distinguish between 'write' mode (which overwrites content) and 'append' mode (which adds to the end) for file operations to avoid data loss.
Question 15. In CSV file, function is used to sort more than one column.
(a) sorter ()
(b) multiplesort ()
(c) itemsort ()
(d) morecolumns ()
Answer: (a) sorter ()
In simple words: To organize data in a CSV file based on values from more than one column, you would use a sorting mechanism. While the specific function might vary, a 'sorter' helps arrange your data according to rules you set for different columns.
π― Exam Tip: Be familiar with methods to sort data, especially across multiple fields, as this is a common operation in data processing. In Python, `sorted()` with `operator.itemgetter()` is typically used.
Question 16. In open command, file name can be represented in
(a) ' '
(b) " "
(c) $
(d) both (a) and (b)
Answer: (d) both (a) and (b)
In simple words: When you specify a file name in the `open()` command in Python, you can put the name inside either single quotes or double quotes. Both ways work the same.
π― Exam Tip: Python is flexible with string literals, allowing both single and double quotes for filenames and other string values, but maintain consistency within your code.
Question 17. method writes a row of data into the specified CSV file.
(a) rows ()
(b) writerow ()
(c) row_data ()
(d) row_write ()
Answer: (b) writerow ()
In simple words: The `writerow()` method from the CSV module is used to add one single line or record of data into a CSV file.
π― Exam Tip: Remember `writerow()` for single rows and `writerows()` for multiple rows when writing to CSV files in Python.
Question 18. Action is used to print the data in dictionary form; t without order.
(a) diet ()
(b) dictionarys ()
(c) read_dict ()
(d) print_dict ()
Answer: (a) diet ()
In simple words: When you read data into Python and want to see it organized like a dictionary (key-value pairs) without a specific order, you often convert it to a dictionary format. The function `dict()` is commonly used for this, allowing you to view the data structured this way.
π― Exam Tip: Be familiar with converting data structures (like lists of lists from `csv.reader`) into dictionaries (often using `csv.DictReader` or `dict()` constructor) for easier key-based access.
Question 19. method will free up the resources that were tied with the file.
(a) freeup ()
(b) open_res ()
(c) resource_close ()
(d) close ()
Answer: (d) close ()
In simple words: After you are done working with a file, you must use the `close()` method. This tells the computer to release the file, so other programs can use it, and it makes sure all your changes are saved.
π― Exam Tip: Always remember to explicitly close files using `file.close()` or use a `with` statement, which handles closing automatically, to prevent resource leaks and data corruption.
Question 21. CSV files are saved with extension
(a) .CV
(b) .CSV
(c) .CVSC
(d) .CSE
Answer: (b) .CSV
In simple words: CSV files are always recognized by their file extension, which is `.CSV`. This helps your computer know it's a Comma Separated Values file.
π― Exam Tip: Knowing standard file extensions like `.csv` is crucial for identifying file types and ensuring compatibility with different software applications.
Question 22. command arranges a CSV file list value in descending order
(a) listname.sort ()
(b) listname.ascd ()
(c) list_name. sort(reverse))
(d) sorting ()
Answer: (c) list_name. sort(reverse))
In simple words: To sort a list of values from a CSV file so that the largest or highest values come first, you use the `sort()` method on the list and tell it to sort in `reverse` order.
π― Exam Tip: Remember that `list.sort(reverse=True)` modifies the list in place for descending order, while `sorted(list, reverse=True)` returns a new sorted list.
Question 23. Which of the following is used to terminate lines produced by the writer?
(a) Linefeed
(b) Delimiters
(c) Line Terminator
(d) SingleQuotes
Answer: (c) Line Terminator
In simple words: When a program writes information to a file, a 'line terminator' is the special character (like a new line) that marks the end of each line of data.
π― Exam Tip: Be aware of the `lineterminator` parameter in the `csv.writer` to control how new lines are handled in the output file, especially across different operating systems.
Question 24. Which format is not allowed to read data from cav files?
(a) quotes
(b) pipe
(c) comma
(d) Asterisk
Answer: (d) Asterisk
In simple words: CSV files usually use commas, pipes, or quotes to separate or enclose data. An asterisk (`*`) is not a standard separator or format for reading data in CSV files.
π― Exam Tip: Recognize common delimiters (comma, tab, pipe) used in text-based data files and identify symbols that are not standard delimiters.
II. Answer The Following Questions (2 And 3 Marks)
Question 1. Compare text mode and binary mode.
Answer: Here is a comparison between text mode and binary mode for file handling:
| Text mode | Binary mode |
|---|---|
| The default is reading in text mode. | Binary mode returns bytes. |
| In this mode, while reading from the file, the data would be in the format of strings. | This is the mode to be used when dealing with non-text files like image or exe files. |
π― Exam Tip: Remember to use text mode (`'t'`) for human-readable content and binary mode (`'b'`) for non-textual data like images or executables to ensure correct file handling.
Question 2. What is the syntax for csv.reader()?
Answer: The syntax for the `csv.reader()` function is:
`csv.reader(fileobject, delimiter, fmtparams)`
Here's what each part means:
- `fileobject`: This is the file that you want to read. It provides the path to the file and indicates the mode in which the file is opened (e.g., read mode).
- `delimiter`: This is an optional parameter. It specifies the character used to separate fields in the CSV file, such as a comma (`,`) or a pipe (`|`). If not specified, the default is a comma.
- `fmtparams`: This is also an optional parameter. It helps you change the default rules of the CSV dialect, like whether to skip initial spaces after a delimiter or how quoting should be handled.In simple words: The `csv.reader()` command helps you read CSV files. You tell it which file to read, what character separates the items (like a comma), and any special rules for how the file is set up.
π― Exam Tip: Clearly understand the role of `fileobject`, `delimiter`, and `fmtparams` as they allow for flexible parsing of various CSV formats.
Question 3. What is the use of the CSV file?
Answer: CSV files are very useful for several reasons:
β’ A CSV file is a straightforward file format. It is used to store data in a table-like structure, similar to a spreadsheet or a simple database.
β’ Because they are plain text, CSV files are easy to move between different programs, making them simpler to import into various spreadsheet applications or other storage systems, no matter what software you are using.In simple words: CSV files are like simple tables for data. They make it easy to share information between different computer programs, like moving data from one spreadsheet to another.
π― Exam Tip: Highlight CSV's key advantage: its simplicity and universal compatibility for data exchange between diverse software applications.
Question 4. Define: Garbage collector
Answer: A garbage collector in Python is a special system that automatically manages memory. It cleans up objects that are no longer being used by the program, freeing up memory space. However, even though Python has a garbage collector, programmers should not completely depend on it to close files. It's always best practice for the user to explicitly close files after they are done with them. This ensures resources are released properly and prevents potential issues.In simple words: Python has a "garbage collector" that cleans up unused memory by itself. But for files, it's still important for you to close them yourself when finished.
π― Exam Tip: Emphasize that while garbage collection handles memory, explicit file closing (or `with` statements) is critical for file resources to ensure data integrity and prevent resource leaks.
Question 5. How to read from CSV file that contains space at the beginning using register dialect() method?
Answer: To read a CSV file that has spaces at the beginning of fields using the `register_dialect()` method:
β’ You can remove these unwanted whitespaces by creating and registering new custom dialects using the `csv.register_dialect()` function. This function uses a dialect class from the `csv` module.
β’ A dialect describes the specific format of the CSV file, including details like `delimiter` and `quoting`. When defining a dialect, you can use a parameter called `"skipinitialspace"`. Setting this parameter to `True` tells the CSV reader to automatically remove any spaces that appear immediately after a delimiter. This ensures that the actual data value starts directly after the separator.In simple words: To read CSV files where there are extra spaces after the commas (or other separators), you can use Python's `register_dialect()` feature. This lets you make a special rule, like saying "skip initial space," so the program ignores those extra spaces and reads only the actual data.
π― Exam Tip: The `skipinitialspace=True` parameter in custom CSV dialects is vital for correctly parsing files where delimiters might be followed by whitespace, preventing leading spaces from becoming part of your data.
Question 6. Define dialect.
Answer: In the context of the Python `csv` module, a 'dialect' is a set of specific rules that describe the format of a CSV file.
β’ A dialect is essentially a class within the `csv` module. It helps define various parameters for how CSV files should be read from or written to.
β’ It lets you create, save, and reuse different groups of formatting settings for your data. These settings include things like the character used for separation (delimiter), how data fields are enclosed (quoting), and what character indicates the end of a line (lineterminator).In simple words: A 'dialect' is like a blueprint for a CSV file. It holds all the specific rules about how the data is laid out, such as what separates each piece of information and how quotes are used. You can make and use these rules again for different files.
π― Exam Tip: Understand that custom dialects are powerful for handling non-standard CSV formats efficiently and consistently in Python.
Question 7. Compare: sort() and sorted ().
Answer: Here's a comparison between the `sort()` method and the `sorted()` function in Python:
β’ The `sort()` method sorts the items of a list in a specific order, either ascending (from smallest to largest) or descending (from largest to smallest). This method changes the original list directly.
β’ The `sorted()` function also sorts elements but works differently from `sort()`. It can sort any type of iterable (like lists, tuples, or strings) and always returns a *new* sorted list, leaving the original iterable unchanged.
β’ The key difference is that `sort()` does not return any value; it changes the original list itself. On the other hand, `sorted()` always gives you a new sorted list back. For example, if you have `my_list = [3, 1, 2]`, `my_list.sort()` makes `my_list` become `[1, 2, 3]`, but `new_list = sorted(my_list)` would make `new_list` be `[1, 2, 3]` while `my_list` remains `[3, 1, 2]`.In simple words: `sort()` changes a list right where it is, without giving you a new list. `sorted()` makes a brand new list that is sorted, leaving the first list as it was.
π― Exam Tip: Differentiate between in-place sorting (`sort()`) and returning a new sorted object (`sorted()`), choosing the appropriate one based on whether you need to preserve the original data structure.
Question 8. Explain how to read CSV file into a dictionary?
Answer: To read a CSV file and store its data as a dictionary in Python, you can use the `DictReader` class from the `csv` module.
β’ The `DictReader` class works similarly to the regular `reader()` class. However, instead of creating a list for each row, it creates an object that maps each row's data to a dictionary. This means you can access values by their field names, not just by their position.
β’ The keys for this dictionary are automatically taken from the field names, which are typically found in the first line of the CSV file. If your CSV file doesn't have a header row, you can provide the field names as parameters.
β’ The data in each following row then behaves like dictionary values. You can easily get to these values using their proper key (which is the fieldname). For example, if you have a header "Name", you can get the name value using `row['Name']`.In simple words: To read a CSV file as a dictionary, Python's `DictReader` turns each row into a dictionary. The column names from the first line become the dictionary keys, making it easy to find data using those names.
π― Exam Tip: The `csv.DictReader` is highly recommended for CSV files with headers, as it provides clear, readable access to data by field name, improving code clarity and maintenance.
Question 9. What are the different formats to create csv files?
Answer: CSV files can be created in several formats depending on how the data is separated and handled:
1. **Default Delimiter (Comma):** This is the most common format where data fields are separated by a comma (`,`). Example: `Name,Age,City`.
2. **Space at the Beginning:** In some cases, there might be an extra space after the delimiter. While not ideal, CSV readers can be configured to `skipinitialspace`. Example: `Name, Age, City`.
3. **With Quotes:** Fields containing special characters (like commas or newlines) or spaces are enclosed in double quotes (`"`). Example: `"John Doe", "New York, USA"`.
4. **With Custom Delimiters:** Instead of commas, other characters like a semicolon (`;`) or a pipe (`|`) can be used as separators. This is useful when the data itself contains commas. Example: `Name;Age;City`.In simple words: CSV files can be made in a few ways: most common is using commas to separate things. Sometimes, you put quotes around data that has commas or new lines inside. You can also use different characters, like a pipe, to separate the data instead of a comma.
π― Exam Tip: Be flexible in recognizing and configuring different CSV formats, especially regarding delimiters and quoting, to ensure correct data parsing.
Question 10. Give the differences between writerow() and writerows() method.
Answer: Here are the differences between the `writerow()` and `writerows()` methods in the Python `csv` module:
| writerow() | writerows() |
|---|---|
| The `writerow()` method writes one row at a time. | The `writerows()` method writes all the data at once to the new CSV file. |
| The `writerow()` method writes one-dimensional data (a single list). | The `writerows()` method writes multi-dimensional data (a list of lists). |
π― Exam Tip: Use `writerow()` when adding data incrementally, and `writerows()` for bulk writing of all data at once, optimizing for efficiency and code readability.
Question 11. Define: Modification
Answer: Modification means making changes to existing data in a file or adding new data to it. This process updates the file's content.
In simple words: When you change information already in a file or put new information into it, that is called modification.
π― Exam Tip: Clearly define "modification" as changing existing data or adding new data to a file.
Question 12. Write a note on Line Terminator.
Answer: A line terminator is a special string that marks the end of a line in a file when the writer produces it. The default line terminators are usually `\r` (carriage return) or `\n` (newline). You can specify a different line terminator when writing a CSV file in Python by registering new dialects using the `csv.register_dialect()` class from the `csv` module. This helps to ensure proper formatting across different systems.
In simple words: A line terminator is a hidden mark that tells a computer when one line of text ends and a new one begins. You can choose what kind of mark to use when saving files.
π― Exam Tip: Remember to mention that line terminators are strings that mark the end of lines and that Python's `csv` module allows custom terminators through dialects.
Question 13. Explain How to write Dictionary into CSV file with custom dialects?
Answer: To write a dictionary into a CSV file with custom dialects, you first need to define your custom dialect using `csv.register_dialect()`. This lets you set specific rules for how the CSV file should be formatted, such as the delimiter (what separates data) and the quoting style. Then, you open the CSV file in write mode, create a `csv.DictWriter` object, and use its `writeheader()` method to write the dictionary keys as a header row. Finally, you use `writerow()` or `writerows()` to write the dictionary data into the file, ensuring the custom rules are applied.
Coding:
`import csv`
`csv.register_dialect('myDialect', delimiter = '|', quoting=csv.QUOTE_ALL)`
`with open('c:\\pyprg\\ch13\\vgrade.csv', 'w') as csvfile:`
` fieldnames = ['Name', 'Grade']`
` writer = csv.DictWriter(csvfile, fieldnames = fieldnames, dialect ="myDialect")`
` writer.writeheader()`
` writer.writerows([{'Grade': 'B', 'Name': 'Anu'},`
` `{'Grade': 'C', 'Name': 'Tarun'}])`
`print("writing completed")`
Output:
| "Name" | "Grade" |
|---|---|
| "Anu" | "B" |
| "Beena" | "A" |
| "Tarun" | "C" |
In simple words: To write dictionary data into a CSV file with special rules, you first set up those rules (like how items are separated) using `csv.register_dialect()`. Then, you use `csv.DictWriter` to put your dictionary information into the file, making sure it follows your custom rules.
π― Exam Tip: Remember that `csv.register_dialect()` is crucial for defining custom formatting rules, and `csv.DictWriter` is used for writing dictionary data, associating keys with column headers.
Question 14. How will you create CSV in text editor?
Answer: To create a CSV file using a simple text editor like Notepad, follow these steps:
- First, open a new file in Notepad (or press Ctrl+N).
- Then, type your data, separating each value with a comma and putting each record on a new line by pressing Enter.
- For example, you can write: `Topic1,Topic2,Topic3`
`one,two,three`
`Example1,Example2,Example3` - Finally, save this content in a file with the `.csv` extension (e.g., `mydata.csv`). Make sure to select "All Files" as the type in the Save As dialog to avoid adding a `.txt` extension.
π― Exam Tip: The key steps are using commas to separate values, new lines for new records, and saving with the `.csv` extension to ensure the file is recognized as a CSV.
Question 15. Explain how to create a new normal CSV file to store data
Answer: Creating a new CSV file to store data typically involves using the `csv.writer()` method. This method returns a writer object that can convert a user's data into comma-separated strings. The `writerow()` method from this object writes a single row of data, while `writerows()` writes multiple rows. The `csv.writer()` syntax includes the file object, a delimiter (like a comma), and optional formatting parameters. For instance, you open a file in write mode (`'w'`), then create a `csv.writer` object from it, and use `writerows()` to write your data, which is usually a list of lists.
| Fileobject | passes the path and the mode of the file. |
|---|---|
| Delimiter: | an optional parameter containing the standard dialects like, | etc can be omitted. |
| Fmtparams: | optional parameter which help to override the default values of the dialects like skipinitialspace, quoting etc. can be omitted. |
Coding:
`import csv`
`csvData = [['Student', 'Age'], ['Dhanush', '17'], ['Kalyani', '18'], ['Ram', '15']]`
`with open('c:\\pyprg\\chl3\\Pupil.csv', 'w') as CF:`
` writer = csv.writer(CF)`
` writer.writerows(csvData)`
`CF.close()`
In simple words: To make a new CSV file, you use the `csv.writer()` tool in Python. This tool helps you take your information, like a list of details, and put it into a file, separating each piece with a comma. You tell it where to save the file and what information to write.
π― Exam Tip: Highlight `csv.writer()` for creating writer objects and `writerows()` for efficiently writing multiple data rows into a new CSV file.
Question 16. Explain how to write CSV Files With Quotes
Answer: To write CSV files with custom quotes, you need to register a new dialect using `csv.register_dialect()` from the `csv` module. This function lets you define the `quoting` parameter, specifying how fields should be quoted. For example, `csv.QUOTE_ALL` ensures that all fields are enclosed in double quotes. This is especially useful when your data itself contains delimiters like commas or newlines, which could otherwise confuse the CSV parser.
Coding:
`import csv`
`info = [['SNO', 'Person', 'DOB'],`
` ['1','Madhu', '18/12/2001'],`
` ['2', 'Sowmya','19/2/1998'],`
` ['3', 'Sangeetha','20/3/1999'],`
` ['4', 'Eshwar', '21/4/2000'],`
` ['5', 'Anand', '22/5/2001']]`
`csv.register_dialect('myDialect',quoting=csv.QUOTE_ALL)`
`with open('c:\\pyprg\\chl3\\person.csv', 'w') as f:`
` writer = csv.writer(f, dialect='myDialect')`
` for row in info:`
` writer.writerow(row)`
`f.close()`
When you open βperson.csv" file, we get following output:
| "SNO" | "Person" | "DOB" |
|---|---|---|
| "1" | "Madhu" | "18/12/2001" |
| "2" | "Sowmya" | "19/2/1998" |
| "3" | "Sangeetha" | "20/3/1999" |
| "4" | "Eshwar" | "21/4/2000" |
| "5" | "Anand" | "22/5/2001" |
In simple words: To write a CSV file where every piece of information is put inside quotation marks, you use Python's `csv.register_dialect()` to set a special rule for quoting. This helps keep your data clear, even if it has commas inside it.
π― Exam Tip: Emphasize the use of `csv.QUOTE_ALL` within `csv.register_dialect()` to ensure all fields are quoted, which is crucial for data integrity.
III. Answer the Following Questions (5 Marks)
Question 1. Explain how to read a specific column in a CSV file.
Answer: To read a specific column from a CSV file, you typically open the file and use the `csv.reader()` object to go through each row. For every row, you can access individual column values using their index (position), starting from 0. For example, `row[0]` would give you the first column, and `row[3]` would give you the fourth column. You iterate through the rows and print or store the values from the desired column indices.
Coding for printing the selected column:
`import csv`
`#opening the csv file which is in different location with read mode`
`f=open("c:\\pyprg\\13ample5.csv",'r') #reading the File with the help of csv.reader()`
`readFile=csv.reader(f)`
`#printing the selected column`
`for col in readFile:`
` print(col[0],col[3])`
`f.close ()`
Sample5.csv File in Excel
| A | B | C | D |
|---|---|---|---|
| item Name | Cost-Rs | Quantity | Profit |
| Keyboard | 480 | 12 | 1152 |
| Monitor | 5200 | 10 | 10400 |
| Mouse | 200 | 50 | 2000 |
Output:
| item Name | Profit |
|---|---|
| Keyboard | 1152 |
| Monitor | 10400 |
| Mouse | 2000 |
In simple words: To read just one column from a CSV file, you open the file and read it row by row. For each row, you pick out the information you need by its position, like picking the first or third item.
π― Exam Tip: Remember to use `csv.reader()` to process rows and access columns by their index (`row[index]`) after opening the file in read mode.
Question 2. Explain how to read the CSV file and store it in a list.
Answer: To read a CSV file and store its contents in a list, you first import the `csv` module. Then, you open the CSV file in read mode (`'r'`). You create a `csv.reader()` object, which allows you to iterate over the lines in the given CSV file. As you loop through each row provided by the reader, you append each row (which is itself a list of strings) to a main list. This results in a list of lists, where each inner list represents a row from the CSV file.
Coding for reading the CSV file and store it in a list:
`import csv`
`inFile= 'c:\\pyprg\\sample.csv'`
`F=open (inFile, 'r')`
`reader = csv.reader(F)`
`arrayValue = []`
`for row in reader:`
` arrayValue.append(row)`
` print(row)`
`F.close()`
Output:
`['Topic1', 'Topic2', 'Topic3']`
`[' one', 'two', 'three']`
`['Example!.', 'Example2', 'Example3']`
In simple words: To get all the data from a CSV file into a list, you open the file and read each line. You then add each line, which is already a small list of items, to a bigger list. So, you end up with one main list containing all the rows as smaller lists.
π― Exam Tip: The core idea is to iterate through the `csv.reader` object and append each `row` (which is a list) into an empty list to collect all data.
Question 3. Explain how to read the CSV file and sort the data in a particular column.
Answer: To read a CSV file and sort its data based on a specific column, you first open the file and create a `csv.reader` object. You might skip the header row if it exists using `next(reader)`. Then, you read all the rows into a list. After that, you can use Python's built-in `sort()` method or `sorted()` function on this list, providing a `key` argument. The key specifies which column (by its index) should be used for sorting. For example, `key=lambda row: row[column_number]` would sort based on the values in the specified column.
Coding for reading the CSV file and sort the data in a particular column:
`import csv`
`inFile= 'c:\\pyprg\\sample6.csv'`
`F=open(inFile,'r')`
`reader = csv.reader(F)`
`next(reader) # skipping the first row(heading)`
`arrayValue = []`
`for row in reader:`
` arrayValue.append(row)`
`a = int(input ("Enter the column number 1 to 3:-"))`
`# sorting a particular column-cost`
`arrayValue.sort(key=lambda x: int(x[a-1]))`
`for row in arrayValue:`
` print (row)`
`F.close ()`
Output:
`Enter the column number 1 to 3:- 2`
`['Keyboard', '480', '12', '1152']`
`['Mouse', '200', '50', '2000']`
`['Monitor', '5200', '10', '10400']`
In simple words: To read and sort a CSV file by one column, you first put all the file's information into a list. Then, you tell the program which column to look at and use a special command to arrange all the rows based on the values in that chosen column.
π― Exam Tip: Remember to read all data into a list first, then use `list.sort()` or `sorted()` with a `key` (often a `lambda` function) to specify the column index for sorting.
Question 4. Explain how to read CSV file with a line Terminator.
Answer: To read and write a CSV file with a specific line terminator, you first register a custom dialect using `csv.register_dialect()`. In this dialect, you can specify the `lineterminator` parameter, for instance, `'\n'` for a Unix-style newline. After defining the dialect, you open the CSV file in write mode (`'w'`), create a `csv.writer` object, and pass your custom dialect to it. When you use `writerows()` to write data, the specified line terminator will be used to end each line in the output file. This ensures consistent line endings, especially important when files are moved between different operating systems.
Coding:
`import csv`
`Data = [['Fruit', 'Quantity'], ['Apple', '5'],`
` ['Banana', '7'], ['Mango', '8']]`
`csv.register_dialect('myDialect', delimiter = '|', lineterminator = '\n')`
`with open('c:\\pyprg\\ch3\\line.csv', 'w') as f:`
` writer = csv.writer(f, dialect='myDialect')`
` writer.writerows(Data)`
`f.close ()`
Output:
| Fruit | Quantity |
|---|---|
| Apple | 5 |
| Banana | 7 |
| Mango | 8 |
In simple words: To read or write a CSV file using a specific end-of-line mark, you set up a special rule (a "dialect") for that mark. Then, when you write the file, each line will end with your chosen mark, making sure it works well on different computers.
π― Exam Tip: Focus on `csv.register_dialect()` and the `lineterminator` parameter for controlling how lines end in a CSV file, especially in cross-platform scenarios.
Question 5. Write a program to set data at runtime and writing it in a CSV file.
Answer: To create a Python program that takes data from the user at runtime and writes it into a CSV file, you can use a loop. First, import the `csv` module and open the CSV file in write mode (`'w'`). Inside a `while` loop, ask the user for each piece of information (like name, date of birth, place) using the `input()` function. Collect these inputs into a list, and then use `csv.writer.writerow()` to write this list as a new row in the CSV file. The loop continues as long as the user wants to add more data. After the data is written, the file is closed. This allows for dynamic data entry directly from the console.
Coding:
`import csv`
`with open ('c:\\pyprg\\ch13\\vdynamicfile.csv', 'w') as f:`
` w = csv.writer(f)`
` ans= 'y'`
` while (ans=='y'):`
` name=input (" Name?:")`
` date=input("Date of birth:")`
` Place=input ("Place:")`
` w.writerow([name, date, place])`
` ans=input("Do you want to enter more y/n?:")`
`F=open('c:\\pyprg\\chl3\\dynamicfile.csv','r')`
`reader=csv.reader (F)`
`for row in reader:`
` print (row)`
`F.close()`
OUTPUT:
`Name?: Nivethitha`
`Date of birth: 12/12/2001`
`Place: Chennai`
`Do you want to enter more y/n?: y`
`Name?: Leena`
`Date of birth: 15/10/2001`
`Place: Nagercoil`
`Do you want to enter more y/n?: y`
`Name?: Padma`
`Date of birth: 18/08/2001`
`Place: Kumbakonam`
`Do you want to enter more y/n?: n`
`['Nivethitha', '12/12/2001', 'Chennai']`
`['Leena', '15/10/2001', 'Nagercoil']`
`['Padma', '18/08/2001', 'Kumbakonam']`
In simple words: This program lets you type in information as it runs, like names and birth dates. It then takes what you type and saves it row by row into a new CSV file. You can keep adding more information until you decide to stop.
π― Exam Tip: The key components are using a `while` loop to repeatedly take `input()` from the user, collecting this input into a list, and then using `writerow()` to add it to the CSV file.
Free study material for Computer Science
TN Board Solutions Class 12 Computer Science Chapter 13 Python and CSV Files
Students can now access the TN Board Solutions for Chapter 13 Python and CSV Files prepared by teachers on our website. These solutions cover all questions in exercise in your Class 12 Computer Science textbook. Each answer is updated based on the current academic session as per the latest TN Board syllabus.
Detailed Explanations for Chapter 13 Python and CSV Files
Our expert teachers have provided step-by-step explanations for all the difficult questions in the Class 12 Computer Science chapter. Along with the final answers, we have also explained the concept behind it to help you build stronger understanding of each topic. This will be really helpful for Class 12 students who want to understand both theoretical and practical questions. By studying these TN Board Questions and Answers your basic concepts will improve a lot.
Benefits of using Computer Science Class 12 Solved Papers
Using our Computer Science solutions regularly students will be able to improve their logical thinking and problem-solving speed. These Class 12 solutions are a guide for self-study and homework assistance. Along with the chapter-wise solutions, you should also refer to our Revision Notes and Sample Papers for Chapter 13 Python and CSV Files to get a complete preparation experience.
FAQs
The complete and updated Samacheer Kalvi Class 12 Computer Science Solutions Chapter 13 Python and CSV Files is available for free on StudiesToday.com. These solutions for Class 12 Computer Science are as per latest TN Board curriculum.
Yes, our experts have revised the Samacheer Kalvi Class 12 Computer Science Solutions Chapter 13 Python and CSV Files as per 2026 exam pattern. All textbook exercises have been solved and have added explanation about how the Computer Science concepts are applied in case-study and assertion-reasoning questions.
Toppers recommend using TN Board language because TN Board marking schemes are strictly based on textbook definitions. Our Samacheer Kalvi Class 12 Computer Science Solutions Chapter 13 Python and CSV Files will help students to get full marks in the theory paper.
Yes, we provide bilingual support for Class 12 Computer Science. You can access Samacheer Kalvi Class 12 Computer Science Solutions Chapter 13 Python and CSV Files in both English and Hindi medium.
Yes, you can download the entire Samacheer Kalvi Class 12 Computer Science Solutions Chapter 13 Python and CSV Files in printable PDF format for offline study on any device.