Topics covered

Python

Sunday, 25 October 2020

How To Print First 'N' Lines Of A File In Python

 In this post we will see how to read first 'N' lines from a .txt file and display it in Python.

To achieve that, first we will consider a "Sample.txt" file which contains the following lines:

Sample.txt:

This is a program to display n lines in python.

In this program we will use readline and range function 

Python is a interpreted and widely use high level programming language


Function To Display Or Print Lines From .Txt File:


#function to print lines in Python
def read_n_lines():
N = 2 #variable to space range of lines to display or print

#open file in read mode
with open("temp.txt", "r") as file:
for i in range(N):
print(file.readline())
file.close()

 So the output of this function will print first two lines of this Sample.txt file as we have specified the range in varaible as N=2

Output:

This is a program to display n lines in python.

In this program we will use readline and range function.

Full Code:


#function to print lines in Python
def read_n_lines():
N = 2 #variable to space range of lines to display or print

#open file in read mode
with open("temp.txt", "r") as file:
for i in range(N):
print(file.readline())
file.close()


#main calling function

def main():
read_n_lines()


if __name__ == '__main__':
main()

Friday, 23 October 2020

How To Convert List Of Dictionary To CSV File In Python

 In this post, we will see how we can convert a list of the dictionary to a CSV file using the Python CSV module.

In this sample python program, we will consider one list of a dictionary that we need to write in a CSV file and also will use dictionary keys as CSV file header.

So let's do it:

Convert Or Write Dictionary To A CSV File In Python

First, we will consider one list of dictionaries. Dictionary is nothing but a key-value pair enclosed within curly braces. 

myDict=[{'id':'1','name':'ABC','address':'home','tell':123456

     }, {'id':'2','name':'DEF', 'address':'home2','tell':12345678

         }, {'id':'3','name':'GHI', 'address':'home3','tell':568445}]


Now we will create one function that will write a list Dictionaries into CSV and print the output. In this function, we used CSV module's DictReader and DictWriter classes.


#function to write Python Dictionary to CSV file
def dict_to_csv():
csv_column = ['id', 'name', 'address', 'tell']
myDict = [{'id': '1', 'name': 'ABC', 'address': 'home', 'tell': 123456

}, {'id': '2', 'name': 'DEF', 'address': 'home2','tell': 12345678

}, {'id': '3', 'name': 'GHI', 'address': 'home3','tell': 568445}]
csv_file = "temp.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, myDict[0].keys())
writer.writeheader()
writer.writerows(myDict)
except IOError:
print("Something went wrong!!!")

Data = csv.DictReader(open(csv_file))
for row in Data:
print(row)

Full Programme Code: 

Below is the full code to write a dict to CSV and print the output:

import csv

#function to write Python Dictionary to CSV file
def dict_to_csv():
csv_column = ['id', 'name', 'address', 'tell']
myDict = [{'id': '1', 'name': 'ABC', 'address': 'home', 'tell': 123456

}, {'id': '2', 'name': 'DEF', 'address': 'home2', 'tell': 12345678

}, {'id': '3', 'name': 'GHI', 'address': 'home3', 'tell': 568445}]
csv_file = "temp.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, myDict[0].keys())
writer.writeheader()
writer.writerows(myDict)
except IOError:
print("Something went wrong!!!")

Data = csv.DictReader(open(csv_file))
for row in Data:
print(row)

#main calling function
def main():
dict_to_csv()


if __name__ == '__main__':
main()

Output:

Below output will get print:

OrderedDict([('id', '1'), ('name', 'ABC'), ('address', 'home'), ('tell', '123456')])

OrderedDict([('id', '2'), ('name', 'DEF'), ('address', 'home2'), ('tell', '12345678')])

OrderedDict([('id', '3'), ('name', 'GHI'), ('address', 'home3'), ('tell', '568445')])

Summation: 

Hope this simplest approach to convert a dictionary to a CSV file in Python can help you in your programming exercise.  





Sunday, 20 September 2020

How To Write A CSV File In Python

In the previous post, we learnt about reading a CSV file in Python. Now in this post, we will learn how to write data into CSV using python's inbuilt writer object.

Writing data to CSV files is very easy and convenient. In Python to write a data or any delimited text to CSV is possible using an inbuilt module name CSV. It has a Writer class i.e. "csv.writer" that returns a writer object.

This writer object has two methods one helps to write one row at a time and another method helps to insert multiple rows at a time. 

In this post we will see writing CSV files using both the methods:

Writing CSV File Using writerow() Method

This method will let you write row-wise data at a time. So let's say we want to write the below data to csv

header=["id", "language", "company"]
row1=["1", "Python", "Development"]
row2=["2", "HTML", "Testing"]
row3=["3", "Java", "Coding"]

So to write the above-mentioned row data, I have defined a write_csv function as mentioned below

def write_csv():
    header = ["id", "language", "company"]
row1 = ["1", "Python", "Development"]
row2 = ["2", "HTML", "Testing"]
row3 = ["3", "Java", "Coding"]

with open('sample_csv1.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(header)
writer.writerow(row1)
writer.writerow(row2)

#main function
def main():
write_csv()


Writing CSV File Using writerows() Method

writerows() method will help to write multiple rows. 

Let's say we have below data in form of lists of lists and we need to write it in CSV

header=["id", "language", "company"]
rows=[["1", "Python", "Development"],
            ["2", "HTML", "Testing"],
            ["3", "Java", "Coding"]]

here how we do it, to write multiple rows using the writer.writerows()

def write_multiple_rows_csv():
header = ["id", "language", "company"]
rows = [["1", "Python", "Development"],
["2", "HTML", "Testing"],
["3", "Java", "Coding"]]
with open('sample_csv1.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(header)
writer.writerows(rows)

#main function
def main():
write_multiple_rows_csv()