Created
October 2, 2022 14:36
-
-
Save yogeshsinghgit/6b671c12da7209332bd43c66ee240cff to your computer and use it in GitHub Desktop.
Reading and Formatting csv file contents in a table using python csv and prettytable library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# importing libraries | |
import csv | |
from prettytable import PrettyTable | |
def readAndFormat(filename): | |
with open(filename) as csvfile: # opeaning csv file in read mode | |
file_contents = csv.reader(csvfile) # reading file content using csv reader function | |
table = PrettyTable() # creating prettytable object | |
file_data = list(file_contents) # creating file object into a list | |
table.field_names = file_data[0] # adding table columns name | |
for data in file_data[1:-1]: | |
if data: | |
table.add_row(data) # adding csv files content as table rows. | |
# calling the function | |
readAndFormat(filename) | |
print(table) | |
readAndFormat("D:\only python\studentData.csv") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment