Python to display data from .csv file

Pie

This code snippet is a simple example how to read .csv files and visualize them.

In our example we have a pie.csv file with the following content:

Pie chart

A;B;C;D

35;25;30;10

The codesnipped reads with the readline() method one line and convert it into the desired data format.

The programm first opens the textfile.

Then the first line with the title is read and the newline character is deleted.

In the secound line the names are read and with the split method converted into a list. The list elements consist now of everything which was separated by an “;”.

The values are formatted like the names but in a last step each list element is converted to a float.

Now a figure is produced and a pie plot with our names and values is generated. Afterwards we set the title and show everything to the user.

#Author: Tobias Markus
import pylab as p
 
filepath = "Pie.csv"
 
f = open(filepath,"r") # open file in readmode
 
title = f.readline()
title = title[0:len(title)-1] # remove \n
 
names = f.readline()
names = names[0:len(names)-1]
names = names.split(";")
 
values = f.readline()
values = values.split(";")
values = map(float,values) # convert list elements to float
 
p.figure(1, figsize=(6,6))
# autopct display the values as defined in the pie
p.pie(values, labels=names,autopct='%.2f') 
p.title(title)
p.show()

 

 

Dieser Beitrag wurde unter Allgemein, Python abgelegt und mit , , , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.