Author name: Shikha Mishra

How to get first key in Dictionary – Python

How to get first key in Dictionary – Python | Get the First Key in Python Dictionary

How to get First Key in a Dictionary Python: In this tutorial, we will discuss different ways to get the first key in a dictionary. Later, we will see & learn how to choose the first N Keys of a dictionary in Python.

Get the first key from a dictionary using keys() method

Dictionary stores elements in key-value pairs.Dictionary act as a container in python. Dictionary provided keys() function which we will use to fetch all keys in it and after that we select the first key from a sequence.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = list(word_freq.keys())[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

In the above example, you can see that first we have fetched all dictionary elements and by using indexing we find out the first key value.

Do Refer:

Here is another way to do the same,

Another Way for How to get First Key in Dictionary Python

By using this method, it will convert all keys of the dictionary to a list and then we can select the first element from the list.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

In the above example, we didn’t call the keys() function. We created a list of keys from the dictionary and selected the first item from it.

Get first key in a dictionary using iter() & next()

What we have done above that was not a perfect solution because first, we created a list and then fetch the first key in a dictionary. It is very difficult to apply that method in a large number of dictionaries. First, we iterate the object of keys using the iter() function then we apply the next() function on it for getting the first element.

Get first key in a dictionary using iter() & next()

This is an efficient solution because didn’t iterate over all the keys in a dictionary, we just selected the first one.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = next(iter(word_freq))
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get the First Key in Dictionary Using list() Function

Also, there is a possible way to convert the dict type into a list using thelist() function at first and later get the first key at the 0th index of the dictionary.

my_dict = { 'Russia': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

print(list(my_dict.keys())[0])

Result:

Russia

Get the First Key in Dictionary Using for Loop

One more easiest way to get the initial key in a dictionary is using theforloop. After getting the first key of the dictionary break the loop.

Let’s see an example on it:

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

for key, value in my_dict.items():
  print(key)
  break

Output:

London

Get first N keys from a Dictionary in Python

To select the first N keys from a dictionary, convert the keys of a dictionary to a list and then select the first N entries from that. For example, let’s see how to select the first 3 keys from a dictionary,

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Conclusion on Get First value in a dictionary of string and int

In this article, we have seen discuss different ways to find out the first key of a dictionary in python. All these dictionary keys methods in python help to find easily the key value in a dictionary of string and int word_freq. Get first key of the dictionary in python information completely from this article.

How to get first key in Dictionary – Python | Get the First Key in Python Dictionary Read More »

Python- How to remove files by matching pattern, wildcards, certain extensions only

Python: How to remove files by matching pattern | wildcards | certain extensions only?

In this ultimate tutorial, we are going to discuss how to remove files from a directory based on a matching pattern or wildcard, or specific extensions.

How to delete text files using different techniques?

Let’s discuss how to delete text files using different techniques, Suppose we have a directory that contains some log files and some text files and we want to delete all .txt files from that directory.

Then, continue your read so that you can successfully learn to remove files by matching patterns or wildcards by the following methods and techniques.

Remove files by pattern using glob.glob() & os.remove()

First, we will get a list of all file paths that match the specified patterns using glob.glob() and then delete all text files.

import os
import glob
# Get a list of all the file paths that ends with .txt from in specified directory
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/*.txt')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)

So you can see that it will remove all ‘.txt’ files in the directory ‘C:\\Users\HP\Desktop\A plus topper\*.txt’. It will remove all text files because we mention” *.txt “.

Get the list of files using glob.glob()

glob.glob() accepts path name and finds the path of all the files that match the specified pattern. By default recursive parameter is False, which means that it will find files in the main directory, not in a subdirectory.

glob.glob(pathname, *, recursive=False)

As we have seen by this approach we can not recursively delete files from subdirectories. For that, we will find another solution,

Read More:

Recursively Remove files by matching pattern or wildcard

It will search all the ‘txt’ files including files in subdirectories because we will use 'C://Users/HP/Desktop/A plus topper/**/*.txt'‘ **  ‘ in it.

Then we can iterate over the list and delete each file one by one using os.remove().

import os
import glob
# get a recursive list of file paths that matches pattern including sub directories
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/**/*.txt', recursive=True)
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except OSError:
        print("Error while deleting file")

It will delete all the text files from the directory and its sub-directories.

Recursively Remove files by matching pattern or wildcard using os.walk()

In this, we are going to use os.walk(). It generates filename in the given directory by walking over the tree structure in a top-down or bottom-up approach.

os.walk(top, topdown=True, onerror=None, followlinks=False)

It will return a tuple consisting of the main directory, a list of all subdirectories, and a list of all file names in the main directory.

Let’s use this os.walk() to get a list of all files in a given directory that matches a pattern. Then delete those files,

import os
import fnmatch
# Get a list of all files in directory
for rootDir, subdirs, filenames in os.walk('C://HP/Users/Desktop/A plus topper'):
    # Find the files that matches the given patterm
    for filename in fnmatch.filter(filenames, '*.txt'):
        try:
            os.remove(os.path.join(rootDir, filename))
        except OSError:
            print("Error while deleting file")

It will delete all the text files from the directory and also from its subdirectories.

Now we are going to create a Generic function to delete all the files from a given directory based on a matching pattern and it will also return the names of the files that were not deleted due to some error.

import os
import fnmatch
'''
Generic function to delete all the files from a given directory based on matching pattern
'''
def removeFilesByMatchingPattern(dirPath, pattern):
    listOfFilesWithError = []
    for parentDir, dirnames, filenames in os.walk(dirPath):
        for filename in fnmatch.filter(filenames, pattern):
            try:
                os.remove(os.path.join(parentDir, filename))
            except:
                print("Error while deleting file : ", os.path.join(parentDir, filename))
                listOfFilesWithError.append(os.path.join(parentDir, filename))
    return listOfFilesWithError
listOfErrors = removeFilesByMatchingPattern('/home/varung/Documents/python/logs/', '*.txt')
print('Files that can not be deleted : ')
for filePath in listOfErrors:
    print(filePath)

So in the above code, you can see that it will also return file names that can not be deleted.

Conclusion:

In this article, we have seen how to remove files from a directory based on matching patterns or wildcards, or certain extensions.

Python: How to remove files by matching pattern | wildcards | certain extensions only? Read More »

numpy.insert() – Python

numpy.insert() – Python | Definition, Syntax, Parameters, Example of Python Numpy.insert() Function

In this tutorial, we will discuss what is python numpy.insert() and how to use numpy.insert()? Also, you can get a good grip on numpy.insert() function in Python by using the example prevailing in this tutorial. Let’s tap on the direct links available here for quick reference on insert an element into NumPy Array in python.

Python numpy.insert()

Python Numpy library provides a function to insert elements in an array. If the insertion is not done in place and the function returns a new array. Moreover, if the axis is not given, the input array is flattened.

Syntax:

numpy.insert(arr, index, values, axis=None)

Parameters:

  • arr: array_like object
    • The array which we give as an input.
  • index: int, slice or sequence of ints
    • The index before which insertion is to be made
  • values: array_like object
    • The array of values to be inserted
  • axis: int, optional
    • The axis along which to insert. If not given, the input array is flattened

Return Values:

  • out: ndarray
    • A copy of arr with given values inserted are given indices.
      • If axis is None, then it returns a flattened array.
      • If axis is 1, then insert column-wise.
      • If axis is 0, then insert row-wise.
    • It doesn’t modify the actual array, rather it returns a copy of the given array with inserted values.

Let’s understand with some of the below-given examples:

numpy.insert() function Example

import numpy as np 
a = np.array([[1,2],[3,4],[5,6]]) 

print 'First array:' 
print a 
print '\n'  

print 'Axis parameter not passed. The input array is flattened before insertion.'
print np.insert(a,3,[11,12]) 
print '\n'  
print 'Axis parameter passed. The values array is broadcast to match input array.'

print 'Broadcast along axis 0:' 
print np.insert(a,1,[11],axis = 0) 
print '\n'  

print 'Broadcast along axis 1:' 
print np.insert(a,1,11,axis = 1)

Output:

First array:
[[1 2]
[3 4]
[5 6]]

Axis parameter not passed. The input array is flattened before insertion.
[ 1 2 3 11 12 4 5 6]

Axis parameter passed. The values array is broadcast to match input array.
Broadcast along axis 0:
[[ 1 2]
[11 11]
[ 3 4]
[ 5 6]]

Broadcast along axis 1:
[[ 1 11 2]
[ 3 11 4]
[ 5 11 6]]

Do Refer: 

Insert an element into a NumPy array at a given index position

Let’s take an array of integers and we want to insert an element 14 at the index position 3. For that, we will call the insert() with an array, index position, and element to be inserted.

import numpy as np
# Create a Numpy Array of integers
arr = np.array([8, 12, 5, 9, 13])
# Insert an element 14 at index position 3
new_arr = np.insert(arr, 3, 14)
print('New Array: ', new_arr)
print('Original Array: ', arr)

Output:

New Array: [ 8 12 5 14 9 13]
Original Array: [ 8 12 5 9 13]

Insert multiple elements into a NumPy array at the given index

In this, we are going to insert multiple elements, for this we pass the elements as a sequence along with the index position.

import numpy as np
# Create a Numpy Array of integers
arr = np.array([8, 12, 5, 9, 13])
# Insert three element at index position 3
new_arr = np.insert(arr, 3, (10, 10, 10))
print('New Array: ', new_arr)

Output:

New Array: [ 8 12 5 10 10 10 9 13]

Insert multiple elements at multiple indices in a NumPy array

In this, we are going to insert multiple elements at multiple indices.

import numpy as np
# Create a Numpy Array of integers
arr = np.array([8, 12, 5, 9, 13])
# Insert three element index position 0, 1 and 2
new_arr = np.insert(arr, (0,1,2), (21, 31, 41))
print('New Array: ', new_arr)

Output:

New Array: [21 8 31 12 41 5 9 13]

So in the above example, you can see that we have added (21,31,41) at (0,1,2) position.

Insert a row into a 2D Numpy array

In this, we are going to insert a row in the array, so we have to pass the axis as 0 and the values as a sequence.

import numpy as np
# Create 2D Numpy array of hard coded numbers
arr = np.array([[2, 3, 4],
                [7, 5, 7],
                [6, 3, 9]])
# Insert a row at index 1
new_arr = np.insert(arr, 1, (4, 4, 4), axis=0)
print(new_arr)

Output:

[[2 3 4]
[4 4 4]
[7 5 7]
[6 3 9]]

Insert a column into a 2D Numpy array

In this, we are going to insert a column in the array, for this we need to pass the axis as 1 and the values as a sequence

import numpy as np
# Create 2D Numpy array of hard coded numbers
arr = np.array([[2, 3, 4],
                [7, 5, 7],
                [6, 3, 9]])
# Insert a column at index 1
new_arr = np.insert(arr, 1, (5, 5, 5), axis=1)
print(new_arr)

Output:

[[2 5 3 4]
[7 5 5 7]
[6 5 3 9]]

So you can see that it inserted a column at index 1.

Here is another way to do the same,

import numpy as np
 # Create 2D Numpy array of hard coded numbers
 arr = np.array([[2, 3, 4],
                 [7, 5, 7], 
                 [6, 3, 9]]) 
# Insert a column at index 1 
new_arr = np.insert(arr, 1,5, axis=1) 
print(new_arr)

Output:

[[2 5 3 4]
[7 5 5 7]
[6 5 3 9]]

Conclusion

In this article, you have seen different uses of numpy.insert(). Thank you!

numpy.insert() – Python | Definition, Syntax, Parameters, Example of Python Numpy.insert() Function Read More »

Pandas- 6 Different ways to iterate over rows in a Dataframe & Update while iterating row by row

Pandas: 6 Different ways to iterate over rows in a Dataframe & Update while iterating row by row

In this tutorial, we will review & make you understand six different techniques to iterate over rows. Later we will also explain how to update the contents of a Dataframe while iterating over it row by row.

Let’s first create a dataframe which we will use in our example,

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])
print(empDfObj)

Output:

Name  Age    City        Experience
a  Shikha 34     Mumbai  5
b Rekha   31     Delhi      7
c Shishir  16     Punjab   11

Iterate over rows of a dataframe using DataFrame.iterrows()

Dataframe class implements a member function iterrows() i.e. DataFrame.iterrows(). Now, we will use this function to iterate over rows of a dataframe.

DataFrame.iterrows()

DataFrame.iterrows() returns an iterator that iterator iterate over all the rows of a dataframe.

For each row, it returns a tuple containing the index label and row contents as series.

Let’s use it in an example,

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

for (index_label, row_series) in empDfObj.iterrows():
   print('Row Index label : ', index_label)
   print('Row Content as Series : ', row_series.values)

Output:

Row Index label : a
Row Content as Series : ['Shikha' 34 'Mumbai' 5]
Row Index label : b
Row Content as Series : ['Rekha' 31 'Delhi' 7]
Row Index label : c
Row Content as Series : ['Shishir' 16 'Punjab' 11]

Note:

  • Do Not Preserve the data types as iterrows() returns each row contents as series however it doesn’t preserve datatypes of values in the rows.
  • We can not able to do any modification while iterating over the rows by iterrows(). If we do some changes to it then our original dataframe would not be affected.

Iterate over rows of a dataframe using DataFrame.itertuples()

DataFrame.itertuples()

DataFrame.itertuples() yields a named tuple for each row containing all the column names and their value for that row.

Let’s use it,

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Iterate over the Dataframe rows as named tuples
for namedTuple in empDfObj.itertuples():
   #Print row contents inside the named tuple
   print(namedTuple)

Output:

Pandas(Index='a', Name='Shikha', Age=34, City='Mumbai', Experience=5)
Pandas(Index='b', Name='Rekha', Age=31, City='Delhi', Experience=7)
Pandas(Index='c', Name='Shishir', Age=16, City='Punjab', Experience=11)

So we can see that for every row it returned a named tuple. we can access the individual value by indexing..like,

For the first value,

namedTuple[0]

For the second value,

namedTuple[1]

Do Read:

Named Tuples without index

If we pass argument ‘index=False’ then it only shows the named tuple not the index column.

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Iterate over the Dataframe rows as named tuples without index
for namedTuple in empDfObj.itertuples(index=False):
   # Print row contents inside the named tuple
   print(namedTuple)

Output:

Pandas(Name='Shikha', Age=34, City='Mumbai', Experience=5)
Pandas(Name='Rekha', Age=31, City='Delhi', Experience=7)
Pandas(Name='Shishir', Age=16, City='Punjab', Experience=11)

Named Tuples with custom names

If we don’t want to show Pandas name every time, we can pass custom names too:

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Give Custom Name to the tuple while Iterating over the Dataframe rows
for row in empDfObj.itertuples(name='Employee'):
   # Print row contents inside the named tuple
   print(row)

Output:

Employee(Index='a', Name='Shikha', Age=34, City='Mumbai', Experience=5)
Employee(Index='b', Name='Rekha', Age=31, City='Delhi', Experience=7)
Employee(Index='c', Name='Shishir', Age=16, City='Punjab', Experience=11)

Iterate over rows in dataframe as Dictionary

Using this method we can iterate over the rows of the dataframe and convert them to the dictionary for accessing by column label using the same itertuples().

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# itertuples() yields an iterate to named tuple
for row in empDfObj.itertuples(name='Employee'):
   # Convert named tuple to dictionary
   dictRow = row._asdict()
   # Print dictionary
   print(dictRow)
   # Access elements from dict i.e. row contents
   print(dictRow['Name'] , ' is from ' , dictRow['City'])

Output:

{'Index': 'a', 'Name': 'Shikha', 'Age': 34, 'City': 'Mumbai', 'Experience': 5}
Shikha is from Mumbai
{'Index': 'b', 'Name': 'Rekha', 'Age': 31, 'City': 'Delhi', 'Experience': 7}
Rekha is from Delhi
{'Index': 'c', 'Name': 'Shishir', 'Age': 16, 'City': 'Punjab', 'Experience': 11}
Shishir is from Punjab

Iterate over rows in dataframe using index position and iloc

We will loop through the 0th index to the last row and access each row by index position using iloc[].

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Loop through rows of dataframe by index i.e. from 0 to number of rows
for i in range(0, empDfObj.shape[0]):
   # get row contents as series using iloc{] and index position of row
   rowSeries = empDfObj.iloc[i]
   # print row contents
   print(rowSeries.values)

Output:

['Shikha' 34 'Mumbai' 5]
['Rekha' 31 'Delhi' 7]
['Shishir' 16 'Punjab' 11]

Iterate over rows in dataframe in reverse using index position and iloc

Using this we will loop through the last index to the 0th index and access each row by index position using iloc[].

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Loop through rows of dataframe by index in reverse i.e. from last row to row at 0th index.
for i in range(empDfObj.shape[0] - 1, -1, -1):
   # get row contents as series using iloc{] and index position of row
   rowSeries = empDfObj.iloc[i]
   # print row contents
   print(rowSeries.values)

Output:

['Shishir' 16 'Punjab' 11]
['Rekha' 31 'Delhi' 7]
['Shikha' 34 'Mumbai' 5]

Iterate over rows in dataframe using index labels and loc[]

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# loop through all the names in index label sequence of dataframe
for index in empDfObj.index:
   # For each index label, access the row contents as series
   rowSeries = empDfObj.loc[index]
   # print row contents
   print(rowSeries.values)

Output:

['Shikha' 34 'Mumbai' 5]
['Rekha' 31 'Delhi' 7]
['Shishir' 16 'Punjab' 11]

Update contents a dataframe While iterating row by row

As Dataframe.iterrows() returns a copy of the dataframe contents in a tuple, so updating it will have no effect on the actual dataframe. So, to update the contents of the dataframe we need to iterate over the rows of the dataframe using iterrows() and then access each row using at() to update its contents.

Let’s see an example,

Suppose we have a dataframe i.e

import pandas as pd


# List of Tuples
salaries = [(11, 5, 70000, 1000) ,
           (12, 7, 72200, 1100) ,
           (13, 11, 84999, 1000)
           ]
# Create a DataFrame object
salaryDfObj = pd.DataFrame(salaries, columns=['ID', 'Experience' , 'Salary', 'Bonus'])

Output:

   ID Experience Salary Bonus
0 11    5             70000 1000
1 12    7             72200 1100
2 13   11            84999 1000

Now we will update each value in column ‘Bonus’ by multiplying it with 2 while iterating over the dataframe row by row.

import pandas as pd


# List of Tuples
salaries = [(11, 5, 70000, 1000) ,
           (12, 7, 72200, 1100) ,
           (13, 11, 84999, 1000)
           ]
# iterate over the dataframe row by row
salaryDfObj = pd.DataFrame(salaries, columns=['ID', 'Experience' , 'Salary', 'Bonus'])
for index_label, row_series in salaryDfObj.iterrows():
   # For each row update the 'Bonus' value to it's double
   salaryDfObj.at[index_label , 'Bonus'] = row_series['Bonus'] * 2
print(salaryDfObj)

Output:

    ID    Experience Salary Bonus
0 11          5           70000 2000
1 12          7           72200 2200
2 13        11           84999 2000

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas

Conclusion:

So in this article, you have seen different ways to iterate over rows in a dataframe & update while iterating row by row. Keep following our BtechGeeks for more concepts of python and various programming languages too.

Pandas: 6 Different ways to iterate over rows in a Dataframe & Update while iterating row by row Read More »

Python numpy.flatten() Function Tutorial with Examples

Python numpy.flatten() Function Tutorial with Examples | How to Use Function Numpy Flatten in Python?

In this tutorial, Beginners and Experience python developers will learn about function numpy.flatten(), how to use it, and how it works. Kindly, hit on the available links and understand how numpy.ndarray.flatten() function in Python gonna help you while programming.

numpy.ndarray.flatten() in Python

A numpy array has a member function to flatten its contents or convert an array of any shape to a 1D numpy array,

Syntax:

ndarray.flatten(order='C')

Parameters:

Here we can pass the following parameters-

Order: In this, we give an order in which items from the numpy array will be used,

C: Read items from array row-wise

F: Read items from array column-wise

A: Read items from array-based on memory order

Returns:

It returns a copy of the input array but in a 1D array.

Also Check:

Let’s learn the concept by viewing the below practical examples,

Flatten a matrix or a 2D array to a 1D array using ndarray.flatten()

First of all, import the numpy module,

import numpy as np

Let’s suppose, we have a 2D Numpy array,

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)

Output:

[7 4 2]
[5 4 3]
[9 7 1]]

Now we are going to use the above 2D Numpy array to convert the 1D Numpy array.

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)
# Convert the 2D array to 1D array
flat_array = arr_2d.flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

[[7 4 2]
[5 4 3]
[9 7 1]]

Flattened 1D Numpy Array:
[7 4 2 5 4 3 9 7 1]

So in the above example, you have seen how we converted the 2D array into a 1D array.

ndarray.flatten() returns a copy of the input array

flatten() function always returns a copy of the given array means if we make any changes in the returned array will not edit anything in the original one.

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)
flat_array = arr_2d.flatten()
flat_array[2] = 50
print('Flattened 1D Numpy Array:')
print(flat_array)
print('Original 2D Numpy Array')
print(arr_2d)

output:

[[7 4 2]
[5 4 3]
[9 7 1]]

Flattened 1D Numpy Array:
[ 7 4 50 5 4 3 9 7 1]

Original 2D Numpy Array
[[7 4 2]
[5 4 3]
[9 7 1]]

Thus in the above example, you can see that it has not affected the original array.

Flatten a 2D Numpy Array along Different Axis using flatten()

It accepts different parameter orders. It can be ‘C’ or ‘F’ or ‘A’, but the default value is ‘C’.
It tells the order.

  • C’: Read items from array row-wise i.e. using C-like index order.
  • ‘F’: Read items from array column-wise i.e. using Fortran-like index order.
  • ‘A’: Read items from an array on the basis of memory order of items.

In the below example, we are going to use the same 2D array which we used in the above example-

Flatten 2D array row-wise

In this, if we will not pass any parameter in function then it will take ‘C’ as a default value

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
flat_array = arr_2d.flatten(order='C')
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[7 4 2 5 4 3 9 7 1]

Flatten 2D array column-wise

If we pass ‘F’ as the order parameter in  function then it means elements from a 2D array will be read column wise

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
flat_array = arr_2d.flatten(order='F')
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[7 5 9 4 4 7 2 3 1]

Flatten 2D array based on memory layout

Let’s create a transparent view of the given 2D array

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
# Create a transpose view of array
trans_arr = arr_2d.T
print('Transpose view of array:')
print(trans_arr)

Output:

Transpose view of array:
[[7 5 9]
[4 4 7]
[2 3 1]]

Now flatten this view was Row Wise,

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
# Create a transpose view of array
trans_arr = arr_2d.T
flat_array = trans_arr.flatten(order='C')
print(flat_array )

Output:

[7 5 9 4 4 7 2 3 1]

Flatten a 3D array to a 1D numpy array using ndarray.flatten()

Let’s create a 3D numpy array,

import numpy as np

# Create a 3D Numpy array
arr = np.arange(12).reshape((2,3,2))
print('3D Numpy array:')
print(arr)

Output:

3D Numpy array:
[[[ 0 1]
[ 2 3]
[ 4 5]]

[[ 6 7]
[ 8 9]
[10 11]]]

Now we are going to flatten this 3D numpy array,

import numpy as np

# Create a 3D Numpy array
arr = np.arange(12).reshape((2,3,2))
# Convert 3D array to 1D
flat_array = arr.flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[ 0 1 2 3 4 5 6 7 8 9 10 11]

Flatten a list of arrays using numpy.ndarray.flatten()

Now, we have to create a list of arrays,

# Create a list of numpy arrays
arr = np.arange(5)
list_of_arr = [arr] * 5
print('Iterate over the list of a numpy array')
for elem in list_of_arr:
    print(elem)

Output:

Iterate over the list of a numpy array
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]

Now, its time to convert the above list of numpy arrays to a flat 1D numpy array,

# Convert a list of numpy arrays to a flat array
flat_array = np.array(list_of_arr).flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]

Flatten a list of lists using ndarray.flatten()

To perform this process, first, we have to create a 2D numpy array from a list of list and then convert that to a flat 1D Numpy array,

# Create a list of list
list_of_lists = [[1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5]]
# Create a 2D numpy array from a list of list and flatten that array
flat_array = np.array(list_of_lists).flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)
# Convert the array to list
print('Flat List:')
print(list(flat_array))

Output:

Flattened 1D Numpy Array:
[1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5]
Flat List:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Hence, this is how we can use flatten() function in numpy.

Conclusion:

We hope this python tutorial, you have seen how to use function numpy.flatten() assist you all in needy times. Thank you! keep visiting our site frequently for updated concepts of python.

Python numpy.flatten() Function Tutorial with Examples | How to Use Function Numpy Flatten in Python? Read More »

Python- How to unzip a file and Extract Single, multiple or all files from a ZIP archive

Python: How to unzip a file | Extract Single, multiple or all files from a ZIP archive | Syntax for ZipFile

In this tutorial, we will discuss different ways to unzip or extract single, multiple, or all files from the zip archive to a current or different directory. Also, you can learn what is a zip file and python unzip file along with the syntax. Moreover, let’s check the reasons to use the Zip Files in python. Click on the direct links available below and happily understand what you required regarding How to unzip files in Python?

What is Zip File?

A ZIP file is a single file containing one or more compressed files, it is an easy way to make large files smaller and keep related files together.

Why do we need zip files?

  • To lessen storage requirements.
  • To develop transfer speed over standard connections.

Python Unzip File

ZipFile class provides a member function to extract all the data from a ZIP archive. ZIP is the archive file format that supports lossless data compression.

In order to unzip a file in Python, make use of this ZipFile.extractall() method. The extractall() method takes a path, members, pwd as an argument, and extracts all the contents.

Also Check:

Syntax for ZipFile

ZipFile.extractall(path=None, members=None, pwd=None)

It accepts three arguments-

1. path: It shows the location where we want to extract our file

2. members:  It shows the list of files to be extracted

3. pwd: If the zip file is encrypted then pass the password in this argument default it will be None

Example of Python unzip

Let’s assume, in my current working directory, I have a zip file called Mail3.zip, and I wanted to unzip it with the help of the ZipFile.extractall() method. So, check out the following example program code:

# app.py

from zipfile import ZipFile

with ZipFile('Mail3.zip', 'r') as zipObj:
   # Extract all the contents of zip file in current directory
   zipObj.extractall()

Output:

python3 app.py

Lets’ first, import the zipfile module in our program,

from zipfile import ZipFile

Extract all files from a zip file to the current directory

So if want to zip file ‘program.zip’. in our current directory, let’s see how to extract all files from it.
To unzip it first create a ZipFile object by opening the zip file in read mode and then call extractall() on that object.

# app.py

from zipfile import ZipFile

with ZipFile('program.zip', 'r') as zipObj:
   # Extract all the contents of zip file in current directory
   zipObj.extractall()

In the output, it will extract the files in the same directory as your programming app.py file.

Extract all files from a zip file to Different Directory

To extract all the files from a zip file to another directory we can pass the destination location as an argument in extractall().

# app.py 
from zipfile import ZipFile
# Create a ZipFile Object and load program.zip in it
with ZipFile('program.zip', 'r') as zipObj:
   # Extract all the contents of zip file in different directory
   zipObj.extractall('temp')

It will extract all the files in ‘program.zip’ in the temp folder.

Extract few files from a large zip file based on condition

If we have a very large zip file and we need a few files from thousand of files in the archive. Unzipping all files from large zip can take minutes. But if we want only a few of the archived files, then instead of unzipping the whole file we can extract a few files too from the zip file.

For this, we are going to use the below syntax-

ZipFile.extract(member, path=None, pwd=None)

It accepts three arguments-

1. path: It shows the location where we want to extract our file

2. members:  Full name of the file to be extracted. It should one from the list of archived files names returned by ZipFile.namelist()

3. pwd: If the zip file is encrypted then pass the password in this argument default it will be None

# app.py 
from zipfile import ZipFile
# Create a ZipFile Object and load program.zip in it
with ZipFile('programDir.zip', 'r') as zipObj:
   # Get a list of all archived file names from the zip
   listOfFileNames = zipObj.namelist()
   # Iterate over the file names
   for fileName in listOfFileNames:
       # Check filename endswith csv
       if fileName.endswith('.csv'):
           # Extract a single file from zip
           zipObj.extract(fileName, 'temp_csv')

It will extract only csv files from the given zip archive.

Conclusion:

So in this article, you have seen how to unzip a file | Extract Single, multiple, or all files from a ZIP archive.

Thank you!

Python: How to unzip a file | Extract Single, multiple or all files from a ZIP archive | Syntax for ZipFile Read More »

Python : How to remove characters from a string by Index ?

Ways to remove i’th character from string in Python

Here we are going to discuss how to remove characters from a string in a given range of indices or at specific index position.

So we will discuss different different methods for this.

Naive Method

In this method, we have to first run the loop and append the characters .After that  build a new string from the existing one .

test_str = "WelcomeBtechGeeks"
  
# Printing original string 
print ("The original string is : " + test_str)
  
# Removing char at pos 3
# using loop
new_str = ""
  
for i in range(len(test_str)):
    if i != 2:
        new_str = new_str + test_str[i]
  
# Printing string after removal  
print ("The string after removal of i'th character : " + new_str)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
The original string is : WelcomeBtechGeeks
The string after removal of i'th character : WecomeBtechGeeks

So in above eoutput you have seen that we have remove character of position three that is ‘l’.

This method is very slow if we compare with other methods.

Using str.replace()

str.replace() can replace the particular index with empty char, and hence solve the issue.

test_str = "WelcomeBtechGeeks"
  
# Printing original string 
print ("The original string is : " + test_str)
  
# Removing char at pos 3
# using replace
new_str = test_str.replace('e', '1')
  
# Printing string after removal  
# removes all occurrences of 'e'
print ("The string after removal of i'th character( doesn't work) : " + new_str)
  
# Removing 1st occurrence of e, i.e 2nd pos.
# if we wish to remove it.
new_str = test_str.replace('e', '', 1)
  
# Printing string after removal  
# removes first occurrences of e
print ("The string after removal of i'th character(works) : " + new_str)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
The original string is : WelcomeBtechGeeks
The string after removal of i'th character( doesn't work) : W1lcom1Bt1chG11ks
The string after removal of i'th character(works) : WlcomeBtechGeeks

So in above output you can see that first we have replace all ‘e’ present in original word.After that we replace only first occurrence of e.This method is also not very useful but sometime we are using this.

Using slice + concatenation

In this method we will use string slicing.Then using string concatenation of both, i’th character can appear to be deleted from the string.

test_str = "WelcomeBtechGeeks"
  
# Printing original string 
print ("The original string is : " + test_str)
  
#Removing char at pos 3
# using slice + concatenation
new_str = test_str[:2] +  test_str[3:]
  
# Printing string after removal  
# removes ele. at 3rd index
print ("The string after removal of i'th character : " + new_str)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
The original string is : WelcomeBtechGeeks
The string after removal of i'th character : WecomeBtechGeeks

Using str.join() and list comprehension

In this method each string is converted in list then each of them is joined to make a string.

test_str = "WelcomeBtechGeeks"
  
# Printing original string 
print ("The original string is : " + test_str)
  
# Removing char at pos 3
# using join() + list comprehension
new_str = ''.join([test_str[i] for i in range(len(test_str)) if i != 2])
  
# Printing string after removal  
# removes ele. at 3rd index
print ("The string after removal of i'th character : " + new_str)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
The original string is : WelcomeBtechGeeks
The string after removal of i'th character : WecomeBtechGeeks

Conclusion:

So in this article we have seen different method to remove characters from a string in a given range of indices or at specific index position.Enjoy learning guys.

Python : How to remove characters from a string by Index ? Read More »

Pandas: Convert a dataframe column into a list using Series.to_list() or numpy.ndarray.tolist() in python

Get a list of a specified column of a Pandas DataFrame

This article is all about how to get a list of a specified column of a Pandas DataFrame using different methods.

Lets create a dataframe which we will use in this article.

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
print(student_df)

Output:

        Name    Age   City             Score
0      Julie      34     Sydney         155.0
1     Ravi       31      Delhi            177.5
2     Aman    16     Mumbai         81.0
3     Mohit    31     Delhi             167.0
4     Veena    12     Delhi             144.0
5      Shan     35    Mumbai         135.0
6     Sradha   35   Colombo        111.0

Now we are going to fetch a single column .

There are different ways to do that.

using Series.to_list()

We will use the same example we use above in this article.We select the column ‘Name’ .We will use [] that gives a series object.Series.to_list()  this function we use provided by the Series class to convert the series object and return a list.

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
list_of_names = student_df['Name'].to_list()
print('List of Names: ', list_of_names)
print('Type of listOfNames: ', type(list_of_names))

Output:

RESTART: C:/Users/HP/Desktop/article2.py
List of Names: ['juli', 'Ravi', 'Aaman', 'Mohit', 'Veena', 'Shan', 'Sradha']
Type of listOfNames: <class 'list'>

So in above example you have seen its working…let me explain in brief..

We have first select the column ‘Name’ from the dataframe using [] operator,it returns a series object names, and we have confirmed that by printing its type.

We used [] operator that gives a series object.Series.to_list()  this function we use provided by the series class to convert the series object and return a list.

This is how we converted a dataframe column into a list.

using numpy.ndarray.tolist()

From the give dataframe we will select the column “Name” using a [] operator that returns a Series object and uses

Series.Values to get a NumPy array from the series object. Next, we will use the function tolist() provided by NumPy array to convert it to a list.

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
list_of_names = student_df['Name'].values.tolist()
print('List of Names: ', list_of_names)
print('Type of listOfNames: ', type(list_of_names))

Output:

RESTART: C:/Users/HP/Desktop/article2.py
List of Names: ['juli', 'Ravi', 'Aaman', 'Mohit', 'Veena', 'Shan', 'Sradha']
Type of listOfNames: <class 'list'>
>>>

So now we are going to show you its working,

We converted the column ‘Name’ into a list in a single line.Select the column ‘Name’ from the dataframe using [] operator,

From Series.Values get a Numpy array

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
names = student_df['Name'].values
print('Numpy array: ', names)
print('Type of namesAsNumpy: ', type(names))

Output:

Numpy array: ['juli' 'Ravi' 'Aaman' 'Mohit' 'Veena' 'Shan' 'Sradha']
Type of namesAsNumpy: <class 'numpy.ndarray'>

Numpy array provides a function tolist() to convert its contents to a list.

This is how we selected our column ‘Name’ from Dataframe as a Numpy array and then turned it to a list.

Conclusion:

In this article i have shown you that how to get a list of a specified column of a Pandas DataFrame using different methods.Enjoy learning guys.Thank you!

Pandas: Convert a dataframe column into a list using Series.to_list() or numpy.ndarray.tolist() in python Read More »

Python Pandas : Select Rows in DataFrame by conditions on multiple columns

About Pandas DataFrame

It  is a 2 dimensional data structure, like a 2 dimensional array, or a table with rows and columns.

This article is all about showing different ways to select rows in DataFrame based on condition on single or multiple columns.

import pandas as pd
students = [ ('Shyam', 'books' , 24) ,
             ('ankur', 'pencil' , 28) ,
             ('Rekha', 'pen' , 30) ,
             ('Sarika', 'books', 62) ,
             ('Lata', 'file' , 33) ,
             ('Mayank', 'pencil' , 30) ] 
dataframeobj = pd.DataFrame(students, columns = ['Name' , 'Product', 'Sale'])
print(dataframeobj)

Output will be:

RESTART: C:/Users/HP/Desktop/dataframe.py
Name    Product    Sale
0   Shyam   books       24
1   Ankur    pencil       28
2   Rekha    pen          30
3   Sarika    books      62
4   Lata       file           33
5   Mayank  pencil     30

Select Rows based on value in column

Let’s see how to Select rows based on some conditions in  DataFrame.

Select rows in above example for which ‘Product’ column contains the value ‘books’,

import pandas as pd
students = [ ('Shyam', 'books' , 24) ,
             ('ankur', 'pencil' , 28) ,
             ('Rekha', 'pen' , 30) ,
             ('Sarika', 'books', 62) ,
             ('Lata', 'file' , 33) ,
             ('Mayank', 'pencil' , 30) ] 
dataframeobj = pd.DataFrame(students, columns = ['Name' , 'Product', 'Sale'])
subsetDataFrame = dataframeobj[dataframeobj['Product'] == 'books']
print(subsetDataFrame)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Name     Product   Sale
0     Shyam    books      24
3     Sarika     books      62

In above example we have seen that subsetDataFrame = dataframeobj[dataframeobj['Product'] == 'books']

using this it will return column which have ‘Product’ contains ‘Books’ only.

So,if we want to see whole functionality?See below.

When we apply [dataframeobj['Product'] == 'books']this condition,it will give output in true & false form.

0 True
1 False
2 False
3 True
4 False
5 False
Name: Product, dtype: bool

It will give true when the condition matches otherwise false.

If we pass this series object to [] operator of DataFrame, then it will be return a new DataFrame with only those rows that has True in the passed Series object i.e.

RESTART: C:/Users/HP/Desktop/dataframe.py

Name     Product   Sale

0     Shyam    books      24

3     Sarika     books      62

If we select any other product name it will return value accordingly.

Select Rows based on any of the multiple values in column

Select rows from above example for which ‘Product‘ column contains either ‘Pen‘ or ‘Pencil‘ i.e

import pandas as pd
students = [ ('Shyam', 'books' , 24) ,
             ('ankur', 'pencil' , 28) ,
             ('Rekha', 'pen' , 30) ,
             ('Sarika', 'books', 62) ,
             ('Lata', 'file' , 33) ,
             ('Mayank', 'pencil' , 30) ] 
dataframeobj = pd.DataFrame(students, columns = ['Name' , 'Product', 'Sale'])
subsetDataFrame = dataframeobj[dataframeobj['Product'].isin(['pen', 'pencil']) ]
print(subsetDataFrame)

We have given product name list by isin() function and it will return true if condition will match otherwise false.

Therefore, it will return a DataFrame in which Column ‘Product‘ contains either ‘Pen‘ or ‘Pencil‘ only i.e.

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Name Product Sale
1 ankur     pencil  28
2 Rekha    pen      30
5 Mayank pencil   30

Select DataFrame Rows Based on multiple conditions on columns

In this method we are going to select rows in above example for which ‘Sale’ column contains value greater than 20 & less than 33.So for this we are going to give some condition.

import pandas as pd
students = [ ('Shyam', 'books' , 24) ,
             ('ankur', 'pencil' , 28) ,
             ('Rekha', 'pen' , 30) ,
             ('Sarika', 'books', 62) ,
             ('Lata', 'file' , 33) ,
             ('Mayank', 'pencil' , 30) ] 
dataframeobj = pd.DataFrame(students, columns = ['Name' , 'Product', 'Sale'])
filterinfDataframe = dataframeobj[(dataframeobj['Sale'] > 20) & (dataframeobj['Sale'] < 33) ]
print(filterinfDataframe)

It will return following DataFrame object in which Sales column  contains value between 20 to 33,

RESTART: C:/Users/HP/Desktop/dataframe.py
    Name      Product Sale
0 Shyam      books    24
1 ankur        pencil    28
2 Rekha       pen       30
5 Mayank    pencil    30

Conclusion:

In this article we have seen diferent methods to select rows in dataframe by giving some condition.Hope you find this informative.

Python Pandas : Select Rows in DataFrame by conditions on multiple columns Read More »

5 Different ways to read a file line by line in Python

Python gives us functions for writing ,creating and reading files.Ok llike we have some file in our directory so in python we can read that file and also make some modification on it. Normal text files and binary files there are two types of files that can be handled in python.There are different ways to read a file line by line in Python.

We have one  file intro1.txt in our directory and we want to read it line by line.Lets see how will we do that.

Using readlines()

readlines() we can use for small file. It reads all files details from memory, then  separate into lines and returns all in a list.  All the List returned by readlines or readline will store the newline character at the end.

Lets take an example,

fileHandler = open ('c:\\new folder\intro1.txt', "r")
# Get list of all lines in file
listOfLines = fileHandler.readlines()
for line in listOfLines:
    print(line.strip()) 
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.

So in above example we have seen that listOfLines = fileHandler.readlines() this will return a list of lines in file. We can iterate over that list and strip() the new line character then print the line .

Above case is only use for small file for large file we have to look up some other methods because it use lots of memory.

Using readline()

For working with large file we have readline().It will read file line by line instead of storing all at one time.Also, if the end of the file is reached, it will return an empty string.

fileHandler = open ("c:\\new folder\intro1.txt", "r")
while True:
    
    line = fileHandler.readline()
    # If line is empty then end of file reached
    if not line :
        break;
    print(line.strip())
   
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. 
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
 Python supports modules and packages, which encourages program modularity and code reuse.

Using context manager (with block)

If we open any file it is very important to close that file,if we did not close then it will automatically close but sometime when there is  large function which not going to end soon.In that case we take help of context manager to cleanup and closeup.

fileHandler = open("c:\\new folder\intro1.txt", "r")
line = fileHandler.readline()
for line in fileHandler:
    print("Line{}: {}".format(count, line.strip()))
   
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py 
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.

After termination of loop file will automatically close,even if there is any exception it will also terminates.

 Using context manager (with block)get List of lines in file

listOfLines = list()        
with open("c:\\new folder\intro1.txt", "r") as file:
    for line in file:
        listOfLines.append(line.strip()) 
    print(listOfLines)

Output:

['Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.', 
"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.", 
'Python supports modules and packages, which encourages program modularity and code reuse.']

So in above example we have iterate all the lines in file and create a list.

Using context manager and while loop read contents of file line by line

So in this method we are going to use while loop and context manager for reading of any file.So in while loop we can give any condition according to this it iterate over lines in file.

with open("c:\\new folder\intro1.txt", "r") as fileHandler:  
    # Read next line
    line = fileHandler.readline()
    # check line is not empty
    while line:
        print(line.strip())
        line = fileHandler.readline()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py
 Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. 
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. 
Python supports modules and packages, which encourages program modularity and code reuse.

Conclusion:

So in this article we have shown you different methods to read any file.Hope you enjoyed the session.

5 Different ways to read a file line by line in Python Read More »