In this tutorial, we will learn how to print rows in Python. Whether you are working with a CSV file or fetching the data from an external API, parsing and printing rows is a common programming problem.
Python, being a versatile language, offers multiple ways to accomplish this task. We will explore these methods in our tutorial.
Step 1 – Read the data
Let’s assume we have a CSV file called data.csv
with the following content:
Name,Age,Gender Alice,25,Female Bob,30,Male Cathy,22,Female David,28,Male Eva,24,Female
In this step, we will read the content of the file into a Python program. We will use the csv
module, which is a built-in Python package for reading and writing CSV files.
1 2 3 4 5 6 |
import csv file = "data.csv" with open(file, "r") as csvfile: data = list(csv.reader(csvfile)) |
Step 2 – Print rows using a for loop
Once we have the data in a list format, we can use a simple for
loop to iterate through the data and print each row.
1 2 |
for row in data: print(row) |
The output will look like this:
['Name', 'Age', 'Gender'] ['Alice', '25', 'Female'] ['Bob', '30', 'Male'] ['Cathy', '22', 'Female'] ['David', '28', 'Male'] ['Eva', '24', 'Female']
Step 3 – Print rows without the header
If you don’t want to print the header row, you can skip the first row in the loop.
1 2 |
for row in data[1:]: print(row) |
The output will look like this:
['Alice', '25', 'Female'] ['Bob', '30', 'Male'] ['Cathy', '22', 'Female'] ['David', '28', 'Male'] ['Eva', '24', 'Female']
Step 4 – Print rows with specific conditions
You can also print rows based on certain conditions. For example, let’s only print the rows where the age is greater than 25.
1 2 3 |
for row in data[1:]: if int(row[1]) > 25: # Age is at index 1 print(row) |
The output will look like this:
['Bob', '30', 'Male'] ['David', '28', 'Male']
Full Code:
Here is the complete code we have discussed above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import csv file = "data.csv" with open(file, "r") as csvfile: data = list(csv.reader(csvfile)) print("Printing all rows:") for row in data: print(row) print("\nPrinting rows without header:") for row in data[1:]: print(row) print("\nPrinting rows with age > 25:") for row in data[1:]: if int(row[1]) > 25: print(row) |
Conclusion
In summary, printing rows in Python is a simple task if you know how to read and manipulate lists. You can use built-in functions such as csv.reader()
to read the data into a list format, and then use a for
loop to iterate through the list and print the rows based on your desired conditions.