Unit III · Basics of Python Programming for Pharmaceutical Sciences (BP101T) · As per PCI B.Pharmacy Syllabus, NEP 2020
Pharmacy datasets rarely start out as neat Python lists and dictionaries — they usually arrive as files: exported inventory sheets, lab results, or patient records saved from a spreadsheet. The CSV format is the simplest and most universal way such data travels between systems. This post explains what a CSV file is, how Python’s built-in csv module reads and writes one, and works through a complete example using patient prescription data.

What Is a CSV File?
A CSV (comma-separated values) file is a plain-text file format used for storing data arranged in rows and columns — that is, in tabular form. In such a file, each row corresponds to one record, each column corresponds to one field of that record, and individual values within a row are separated using a delimiter, most commonly the comma character. Because the format is so simple and entirely text-based, CSV files are widely used to transfer or exchange data between different software systems and applications, from Excel to a Python script to a hospital database.
How a CSV File Is Structured
A typical CSV file follows a two-part structure. The very first row is generally reserved for headers — it lists the names of the columns or fields. Every row that follows the header holds the actual data values for those fields.
Consider a small CSV file with the header row Name,Drug,Dose followed by a data row Rahul,Paracetamol,500. The header row tells us each record has three fields named Name, Drug, and Dose; the data row supplies one actual record — a patient named Rahul given the drug Paracetamol at a dose of 500 units.
Characteristics of CSV Files
- Simple and human-readable — the contents can be opened and understood directly by a person, since it is just plain text separated by commas.
- Platform-independent — not tied to any particular operating system or software; it opens on virtually any platform.
- Stores data in text format — every value, regardless of its original type, is saved as text characters.
- Lightweight — with no special formatting, styling, or binary content, file sizes stay small.
- No strict schema enforcement — a CSV file does not force a rigid structure or fixed data types on its columns.
File Handling Modes in Python
Before a program can read or write a CSV file, the file must be opened in a mode that tells Python what kind of access is required.
| Mode | Meaning |
|---|---|
| “r” | Opens the file for reading only. |
| “w” | Opens the file for writing; overwrites existing content. |
| “a” | Opens in append mode; new data is added after existing content. |
| “r+” | Opens the file for both reading and writing at once. |
Reading a CSV File
Reading a CSV file means opening it and extracting its stored data one row at a time so a program can process it. The general workflow has four steps: open the file in read mode, create a CSV reader object to interpret its contents, iterate through the rows the reader supplies, and access the required values from each row.
Two Ways to Read CSV Data
Python’s built-in csv module offers two common approaches. csv.reader() reads each row as a plain list of values, so every row is a Python list. csv.DictReader() reads each row as a dictionary instead, using the column names from the header row as keys — generally considered more structured and easier to work with, since you can refer to a field by name (row["Dose"]) rather than by position (row[2]).
import csv
# Reading with csv.reader() - each row comes back as a list
with open("patients.csv", "r") as file:
reader = csv.reader(file)
header = next(reader) # skip/capture the header row
for row in reader:
print(row) # e.g. ['Rahul', 'Paracetamol', '500']
# Reading with csv.DictReader() - each row comes back as a dictionary
with open("patients.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
dose = int(row["Dose"]) # convert text to an integer
print(row["Name"], dose + 50)
Two points matter regardless of which reader you use. First, every value read from a CSV file is treated as a string by default — if the data is meant to be numeric, an explicit type conversion such as int() or float() must be performed afterward. Second, the header row must be handled correctly, since it identifies the fields rather than holding an actual data record.
Writing a CSV File
Writing to a CSV file means taking data from a program and storing it into the file in the proper, structured, comma-separated format. The basic steps are: open or create the file in write (“w”) or append (“a”) mode, create a CSV writer object, then add the required rows or records.
csv.writer() vs csv.DictWriter()
csv.writer() writes records row by row, with data generally supplied as lists or sequences. csv.DictWriter() allows records to be written using dictionaries instead, but requires the column (field) names to be specified up front via fieldnames.
import csv
# Writing with csv.writer()
with open("new_patients.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Drug", "Dose"]) # header
writer.writerow(["Rahul", "Paracetamol", 500]) # data row
writer.writerow(["Anita", "Ibuprofen", 400])
# Writing with csv.DictWriter()
with open("new_patients.csv", "a", newline="") as file:
fieldnames = ["Name", "Drug", "Dose"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writerow({"Name": "Vikram", "Drug": "Amoxicillin", "Dose": 250})
A few options come up constantly when writing files. “w” mode creates a new file or replaces the contents of an existing one, while “a” mode adds new records to the end without removing what’s already there. The newline="" argument prevents unwanted blank lines from appearing between records on some operating systems (notably Windows) and should be included as a habit whenever you open a file for CSV writing. Finally, remember that values may need explicit conversion into the right form — a string, integer, or float — before being written.
newline="". This is a well-known, specific gotcha that examiners like to test.Advantages and Limitations of CSV Files
CSV files are popular because they are simple to create and modify, compatible with spreadsheet applications such as Microsoft Excel, small and lightweight, and supported by virtually every programming language and software application in use today.
They do have real limitations, though. A CSV file does not inherently preserve specific data types — everything is text until you convert it. It cannot represent relationships between data the way a relational database can. It offers limited security and access control. And it becomes less suitable once a dataset grows very large or highly complex, at which point a proper database or a format like Excel with typed columns becomes more appropriate.
Frequently Asked Questions
Why does every value read from a CSV file need to be converted with int() or float()?
Because a CSV file is pure text. Even a number like 500 is stored as the characters “5”, “0”, “0” and comes back from csv.reader() or csv.DictReader() as the string "500", not the integer 500. If you try to do arithmetic on it directly, Python will either raise a TypeError or silently concatenate strings instead of adding numbers, so an explicit conversion is required first.
What’s the practical difference between csv.reader() and csv.DictReader()?
csv.reader() gives you each row as a list, so you must remember that column 2 means “Dose” — fragile if column order ever changes. csv.DictReader() gives you each row as a dictionary keyed by the header names, so row["Dose"] is clear, self-documenting, and safe even if columns get reordered.
What happens if I open an existing file in “w” mode by mistake?
Python immediately truncates (empties) the file the moment it is opened in “w” mode, before you write anything new. Any previously stored records are lost as soon as the file is opened this way, so always double-check whether you need “w” (overwrite) or “a” (append) before running your script.
Summary
CSV files store tabular pharmacy data as plain, comma-separated text, with a header row defining fields and each following row holding one record. Python’s built-in csv module reads files using csv.reader() (rows as lists) or the more convenient csv.DictReader() (rows as dictionaries keyed by column name), and writes files using csv.writer() or csv.DictWriter(). Because every value in a CSV file is stored as text, explicit type conversion is always required before doing arithmetic, and the file mode (“r”, “w”, “a”, or “r+”) must be chosen carefully to avoid accidentally overwriting existing data.
References
- Pharmacy Council of India (PCI), B.Pharm Regulations, NEP 2020 — BP101T Syllabus, Basics of Python Programming for Pharmaceutical Sciences
- Python Software Foundation, “csv — CSV File Reading and Writing” — official Python documentation, docs.python.org
- Python Software Foundation, “Reading and Writing Files” — official Python tutorial, docs.python.org
