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.