ใJust Copy & PasteใLet's Build a Web App to Read and Display CSV Data with Python!
A must-read for programming beginners! This article provides a super-detailed guide on how to create a simple web application that reads a CSV file using Python and displays its contents in a table on a web browser. No expert knowledge required. Just copy and paste the code, and you'll have a working app on your computer. Experience the thrill of "It works!" for yourself.
Introduction: Just a Few Months Ago, I Was in the Same Boat as You
Hello! I'm the author of this article, and just a few months ago, I was a complete beginner who didn't know the first thing about programming. I'd get stuck on every error and almost gave up many times, thinking, "Maybe this isn't for me..."
But, through trial and error with AI (Artificial Intelligence) as my partner, I gradually started to understand code. Before I knew it, I had single-handedly launched two websites in a month and a half (buyonjapan.com, copicode.com).
This article is exactly what I wish I had read back then. I've written it from a beginner's perspective, sharing the stumbling blocks I faced and how I solved them. I'll avoid jargon as much as possible, and when I do use it, I'll explain it simply, so you can follow along with confidence.
STEP 1: Let's Prepare for App Development (Environment Setup)
First, let's get ready to build the app. Think of this as the "gathering ingredients and tools" step in cooking. It's not difficult, so let's go through it one by one.
1. Setting Up Python and Flask
This app is built using a programming language called Python and a tool called Flask (which, in technical terms, is a "web framework").
Flask is like a magic box that makes creating web apps with Python incredibly easy. First, let's install Flask on your computer.
Open the "Terminal" on your computer (or "Command Prompt" or "PowerShell" on Windows), copy and paste the following command, and run it.
pip install Flask
*Don't worry if you're wondering, "What is pip?" Just think of it as a command that comes with Python for adding useful tools (libraries).
2. Preparing the Working Folder and Files
Next, let's create a place (a folder) to store our app's blueprints and materials. Create a new folder named "csv_app" anywhere you like on your computer.
Then, create the following three items inside that "csv_app" folder.
- app.py: The Python blueprint file that defines the main logic of the app.
- data.csv: The CSV file containing the data you want to display in the browser.
- A templates folder
- Inside this folder, create index.html. This file defines the appearance of the page displayed in the browser.
Your folder structure should look like this:
csv_app/
โโโ app.py
โโโ data.csv
โโโ templates/
โโโ index.html
ใKey PointใYou must place the HTML file inside a folder named "templates". This is a Flask rule; it's a convention to tell Flask, "Hey, the page layout files are in here." If you use a different name, you'll get an error, so be careful.
STEP 2: Let's Prepare the Data to Display (data.csv)
Next, let's prepare the CSV data for our app. Copy and paste the following content into the data.csv file you created and save it.
For this example, we'll use a simple member list.
ID,Name,Email,RegistrationDate
1,Yuko Sato,yuko.sato@example.com,2024-05-01
2,Kenta Suzuki,kenta.suzuki@example.com,2024-05-15
3,Asuka Takahashi,asuka.takahashi@example.com,2024-06-03
4,Wataru Tanaka,wataru.tanaka@example.com,2024-06-21
5,Sakura Ito,sakura.ito@example.com,2024-07-10
A Point of Caution: Character Encoding
When you save the file, we recommend setting the character encoding to "UTF-8". This is like a universal rule for computers to understand characters. Using it prevents the phenomenon of "mojibake," where text might show up as "???".
When I was a beginner, I spent hours struggling with this character encoding issue... If your app doesn't work correctly and you see garbled text, the first thing you should check is the character encoding of this CSV file.
STEP 3: Let's Write the Python Program to Run the Server (app.py)
Now for the main program! Copy and paste the entire code below into your app.py file. I'll explain what each part means in detail after the code block.
# Import the necessary tools (libraries)
from flask import Flask, render_template
import csv
# Create the main Flask app instance
app = Flask(__name__)
# Define the process for when a specific URL is accessed
@app.route('/')
def index():
# Prepare to open and read the CSV file
# Specify encoding='utf-8' to prevent garbled text
with open('data.csv', 'r', encoding='utf-8') as file:
# Use the csv module's reader to read the comma-separated data
csv_reader = csv.reader(file)
# Read the first line (the header) first
header = next(csv_reader)
# Read the remaining data rows into a list
data = [row for row in csv_reader]
# Pass the data to the HTML and generate the page
return render_template('index.html', header=header, data=data)
# If this file is executed directly, start the web server
if __name__ == '__main__':
# Setting debug=True is convenient as the server will automatically restart when you modify the code
app.run(debug=True)
Code Explanation (A Quick Overview)
from flask import ...,import csv
This is like a magic spell to enable the useful toolboxes named "Flask" and "csv" that we're about to use.app = Flask(__name__)
This creates the main body of the Flask app. It's a standard convention, so for now, just accept it as "this is how you write it."@app.route('/')
This is like an instruction sheet that says, "When a request comes to the website's top page ('/'), run the function right below it (index())."def index():
This is the actual process that runs when the top page is accessed.with open(...): This opens the CSV file. Theencoding='utf-8'part is a key point for preventing garbled text. Usingwithis convenient because it automatically closes the file after the process is finished.csv.reader(file): This is a function that takes the opened CSV file and splits it by commas, making it easy for Python to handle.header = next(csv_reader): This takes the first line of the CSV file (ID, Name, ...) and stores it as the "header."data = [row for row in csv_reader]: This takes all the remaining data rows and stores them in a list (a collection of data) named "data."
return render_template(...)
This is the most crucial part. It's an order to Flask, saying, "Please create a web page using the layout file namedindex.html! And while you're at it, I'm passing along theheaderanddatainformation I just read, so use that too!"if __name__ == '__main__': ...
This is a standard phrase for starting the development web server when this Python file is run directly.
It might look like a bunch of spells at first, but you'll be fine once you understand the simple flow of "read the file" and "pass it to HTML"!
STEP 4: Let's Create the Display Layout (HTML) (templates/index.html)
Next, we'll create the HTML file that will act as the "container" for displaying the data passed from Python. Copy and paste the following code into the index.html file inside your templates folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSV Data Viewer App</title>
<!-- Simple styles for dark mode -->
<style>
body {
background-color: #202124;
color: #e8eaed;
font-family: sans-serif;
padding: 2rem;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
}
th, td {
border: 1px solid #5f6368;
padding: 12px;
text-align: left;
}
th {
background-color: #3c4043;
color: #e8eaed;
}
</style>
</head>
<body>
<h1 style="color: #669df6;">CSV Data List</h1>
<!-- Display the table if data exists -->
{% if data %}
<table>
<thead>
<tr>
<!-- Display the header passed from Python -->
{% for col in header %}
<th>{{ col }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<!-- Display the data passed from Python row by row -->
{% for row in data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No data to display.</p>
{% endif %}
</body>
</html>
Special Symbols in the HTML: {% ... %} and {{ ... }}
You might notice some unfamiliar symbols in this HTML code, like {% ... %} and {{ ... }}. This is the syntax for Jinja2, the template engine that Flask uses.
{% for ... %} ... {% endfor %}
This serves the same purpose as a "for loop" in Python. It means, "Repeat the HTML inside here for each piece of data passed from Python." This allows you to automatically generate 5 table rows if you have 5 rows of data, or 100 rows if you have 100.{{ ... }}
This is a placeholder for displaying the "content" of a variable passed from Python.{{ col }}displays the column name from the header, and{{ cell }}displays the content of each data cell.
By separating Python (data processing) from HTML (presentation) like this, your code becomes easier to manage and it's simpler to build more complex apps. This is one of the major benefits of using a framework like Flask.
STEP 5: Let's Run the App!
Alright, all preparations are complete! It's finally time to run the app.
Open your terminal (or Command Prompt) again and use the cd command to navigate to the "csv_app" folder you created earlier.
Then, run the following command:
python app.py
After running the command, you should see a message like this in your terminal:
* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: ...
If you see a message like "Running on http://127.0.0.1:5000", it's a success! A web server is now running on your computer.
Open your web browser (like Google Chrome) and copy and paste the following URL into the address bar:
How does it look? The contents of data.csv should now be displayed in a neat table in your browser! This is the web application you built with Python. Congratulations! ๐
ใBonus SectionใMaking It Even Easier with Pandas!
The current method works just fine, but Python has an incredibly powerful library for data analysis called Pandas. Using it makes reading CSV files and converting them to HTML even simpler.
If you're interested, definitely give this a try.
1. Installing Pandas
First, let's install Pandas. In your terminal (after stopping the server with Ctrl+C), run this command:
pip install pandas
2. Modifying app.py
Rewrite app.py as follows. Can you see how much shorter the CSV reading part has become?
from flask import Flask, render_template
import pandas as pd # import pandas as pd
app = Flask(__name__)
@app.route('/')
def index():
# Read the CSV file using Pandas (just one line!)
df = pd.read_csv('data.csv', encoding='utf-8')
# Convert the DataFrame to an HTML table tag (also one line!)
# You can specify CSS classes with the classes attribute, remove the border with border=0, etc.
html_table = df.to_html(classes='data-table', index=False, border=0)
# Pass the table data to the HTML to generate the page
return render_template('index_pandas.html', table=html_table)
if __name__ == '__main__':
app.run(debug=True)
3. Creating index_pandas.html
Since Pandas generates the entire HTML for the table, the HTML file itself also becomes simpler. Create a new file named index_pandas.html in your templates folder and paste the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSV Data Viewer App (Pandas Version)</title>
<style>
body {
background-color: #202124;
color: #e8eaed;
font-family: sans-serif;
padding: 2rem;
}
/* Apply styles to the class name specified in to_html */
.data-table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
}
.data-table th, .data-table td {
border: 1px solid #5f6368;
padding: 12px;
text-align: left;
}
.data-table thead th { /* Header row styles */
background-color: #3c4043;
color: #e8eaed;
}
</style>
</head>
<body>
<h1 style="color: #669df6;">CSV Data List (Pandas Version)</h1>
<!-- Display the HTML table passed from Python(Pandas) as is -->
{{ table|safe }}
</body>
</html>
The key part is {{ table|safe }}. The HTML code generated by Pandas includes tags like <table>, so we add the |safe filter to tell Flask, "This is safe HTML, so please render it as is."
If you run python app.py again and access the page, a similar table should be displayed. The code is much cleaner, and the door to more advanced data manipulation has been opened!
Conclusion: A Small "I Did It!" Becomes a Big Step Forward
In this article, we created a simple web app to display CSV data in a browser using Python and Flask. Were you able to experience the "just copy and paste and it works" feeling?
Learning to program is like climbing a huge mountain. If you aim for the summit from the very beginning, you'll get discouraged by the steepness. But if you clear small goals one by one, like "First, let's get to the base camp," or "Next, let's reach that hill with the nice view," you can steadily make your way to the top.
I would be overjoyed if the small success of "The code I wrote (or pasted) made a web app work!" that you experienced in this article gives you the confidence to take your next step.
From here, try making your own modifications, like "Let's add a search function," or "Let's make the data editable." It's okay if you get errors; they are part of the learning process. Please enjoy the fun of building your own unique app while asking AI for help or searching for error messages online.
Bonus: The Complete "All-in-One" HTML Source Code (Browser Output)
For your reference, here is the actual HTML source code that is generated in the web browser when you run the first app we created (the standard library version). It can be helpful for grasping the image of how the Python program dynamically creates this HTML based on the contents of the CSV file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSV Data Viewer App</title>
<!-- Simple styles for dark mode -->
<style>
body {
background-color: #202124;
color: #e8eaed;
font-family: sans-serif;
padding: 2rem;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
}
th, td {
border: 1px solid #5f6368;
padding: 12px;
text-align: left;
}
th {
background-color: #3c4043;
color: #e8eaed;
}
</style>
</head>
<body>
<h1 style="color: #669df6;">CSV Data List</h1>
<!-- Display the table if data exists -->
<table>
<thead>
<tr>
<!-- Display the header passed from Python -->
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>RegistrationDate</th>
</tr>
</thead>
<tbody>
<!-- Display the data passed from Python row by row -->
<tr>
<td>1</td>
<td>Yuko Sato</td>
<td>yuko.sato@example.com</td>
<td>2024-05-01</td>
</tr>
<tr>
<td>2</td>
<td>Kenta Suzuki</td>
<td>kenta.suzuki@example.com</td>
<td>2024-05-15</td>
</tr>
<tr>
<td>3</td>
<td>Asuka Takahashi</td>
<td>asuka.takahashi@example.com</td>
<td>2024-06-03</td>
</tr>
<tr>
<td>4</td>
<td>Wataru Tanaka</td>
<td>wataru.tanaka@example.com</td>
<td>2024-06-21</td>
</tr>
<tr>
<td>5</td>
<td>Sakura Ito</td>
<td>sakura.ito@example.com</td>
<td>2024-07-10</td>
</tr>
</tbody>
</table>
</body>
</html>