Fileno python – Python File fileno() Method with Examples

Python File fileno() Method with Examples

Files in Python:

Python fileno: Python file handling is a way of saving program output to a file or reading data from a file. File handling is a crucial concept in the programming world. File management is used in almost every form of project. Assume you are constructing an inventory management system. You have data in the inventory management system related to sales and purchases, thus you must save that data somewhere. Using Python’s file management, you can save that data to a file. You must be given data in the form of a comma-separated file or a Microsoft Excel file if you wish to conduct data analysis. Using file handling, you can read data from a file and write output back into it.

fileno() Method in Python:

fileno python: The fileno() function is a built-in Python method that returns the file number, i.e. the file descriptor, as an integer of the stream. If the operating system does not use a file descriptor when the file is closed, it may return an error.

Syntax:

file.fileno()

Parameters: This method doesn’t accept any parameters

Return Value: This method’s return type is class ‘int’>; it returns an integer value that is the file descriptor of a file.

File fileno() Method with Examples in Python

Example1: (File in read-mode)

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Get the file descriptor of a file using the fileno() function and store it in a variable.
  • Print the above result.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
gvn_file = open(givenFilename, 'r') 
# Get the file descriptor of a file using the fileno() function and store it in a variable
rslt= gvn_file.fileno()
# Print the above result
print(rslt)

Output:

60

File Content:

hello this is btechgeeks

Example2: (File in write-mode)

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in write mode. In this case, we’re simply writing the contents into the file.
  • Get the file descriptor of a file using the fileno() function and store it in a variable.
  • Print the above result.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in write mode. In this case, we're simply writing the contents into the file.
gvn_file = open(givenFilename, 'w') 
# Get the file descriptor of a file using the fileno() function and store it in a variable
rslt= gvn_file.fileno()
# Print the above result
print(rslt)

Output:

60

Example3:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in write mode. In this case, we're simply writing the contents into the file.
gvn_file = open(givenFilename, 'w') 
# Get the file descriptor of a file using the fileno() function and store it in a variable
rslt= gvn_file.fileno()
# Print the above result
print(rslt)
# Close the given file using the close() function
gvn_file.close()
# Again print the file descriptor of a file using the fileno() function 
print(gvn_file.fileno())

Output:

ValueError                                Traceback (most recent call last)
<ipython-input-26-159a8df3b386> in <module>()
     11 gvn_file.close()
     12 # Again print the file descriptor of a file using the fileno() function
---> 13 print(gvn_file.fileno())

ValueError: I/O operation on closed file

Explanation:

It raises an error because when attempting to display the file descriptor 
after closing the file, an error message will be returned.

Google Colab Images:

Files and Code:

Numpy reciprocal – Python NumPy reciprocal() Function

Python NumPy reciprocal() Function

NumPy reciprocal() Function:

Numpy reciprocal: The reciprocal() function of the NumPy module calculates the reciprocal of all the elements in the input array.

In terms of array broadcasting, it is similar to 1/a.

Syntax:

numpy.reciprocal(a, out=None, dtype=None)

Parameters

a: This is required. It is an array given as input.

out: This is optional. It is the location where the result will be saved. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.

dtype: This is optional. It indicates the data type of the array that will be returned.

Return Value: 

The element-by-element reciprocal of the given array is returned.

NumPy reciprocal() Function in Python

Example1: (For 1-Dimensional Array)

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list (1-Dimensional) as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the above-given array, datatype as a float as the arguments to the reciprocal() function of the numpy module to get the element-by-element reciprocal of the given array.
  • Store it in another variable.
  • Print the element-by-element reciprocal of the given array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list() as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([-10, 6, 4, 3, -20, 1])           
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array, datatype as int as the arguments to the reciprocal() 
# function of the numpy module to get the element-by-element reciprocal of the given array
# Store it in another variable.
rslt = np.reciprocal(gvn_arry, dtype=float)
# Print the element-by-element reciprocal of the given array.
print("The element-by-element reciprocal of the given array:")
print(rslt)

Output:

The above given array is:
[-10 6 4 3 -20 1]
The element-by-element reciprocal of the given array:
[-0.1 0.16666667 0.25 0.33333333 -0.05 1. ]

Example2: (For n-Dimensional Array)

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list (3-Dimensional) as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the above-given array, datatype as float as the arguments to the reciprocal() function of the numpy module to get the element-by-element reciprocal of the given array.
  • Store it in another variable.
  • Print the element-by-element reciprocal of the given array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list(3-Dimensional) as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[10, 6, 4],[5, 10, 50],[20, 10, 8]])           
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array, datatype as float as the arguments to the reciprocal() 
# function of the numpy module to get the element-by-element reciprocal of the given array
# Store it in another variable.
rslt = np.reciprocal(gvn_arry, dtype=float)
# Print the element-by-element reciprocal of the given array.
print("The element-by-element reciprocal of the given array:")
print(rslt)

Output:

The above given array is:
[[10 6 4]
 [ 5 10 50]
 [20 10 8]]
The element-by-element reciprocal of the given array:
[[0.1 0.16666667 0.25 ]
 [0.2 0.1 0.02 ]
 [0.05 0.1 0.125 ]]

Divide all elements of list python – Python Program Divide all Elements of a List by a Number

Program Divide all Elements of a List by a Number

Divide all elements of list python: In the previous article, we have discussed Python Program to Get Sum of all the Factors of a Number

Given a list, and the task is to divide all the elements of a given List by the given Number in Python

As we know, elements such as int, float, string, and so on can be stored in a List. As we all know, dividing a string by a number is impossible. To divide elements of a list, all elements must be int or float.

Examples:

Example1:

Input:

Given List = [3, 2.5, 42, 24, 15, 32]
Given Number = 2

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Example 2:

Input:

Given List =  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Given Number = 5

Output:

The above given list after division all elements of a List by the given Number= [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

Program Divide all Elements of a List by a Number

Python divide list by number: Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Below are the ways to divide all Elements of a List by a Number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gven_Lst = [3, 2.5, 42, 24, 15, 32]
# Give the number as static input and store it in another variable.
gvn_numb = 2
# Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator  by  the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using the For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • Print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

#Give the list as user input using list(),map(),input(),and split() functions.
gven_Lst = list(map(float, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in another variable.
gvn_numb = int(input("Enter some random number = " ))
#Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator by the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

Enter some random List Elements separated by spaces = 4 5 8 9.6 15 63 32 84
Enter some random number = 4
The above given list after division all elements of a List by the given Number= [1.0, 1.25, 2.0, 2.4, 3.75, 15.75, 8.0, 21.0]

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python invert dictionary – Python Program to invert a Dictionary

Program to invert a Dictionary

Python invert dictionary: In the previous article, we have discussed Python Program to Check if two Lines are Parallel or Not
Dictionary in python:

Python includes a class dictionary, which is typically defined as a set of key-value pairs. In Python, inverting a dictionary means swapping the key and value in the dictionary.

One thing is certain: complexity can be found in all of the different ways of storing key-value pairs. That is why dictionaries are used.

Python dictionaries are mutable collections of things that contain key-value pairs. The dictionary contains two main components: keys and values. These keys must be single elements, and the values can be of any data type, such as list, string, integer, tuple, and so on. The keys are linked to their corresponding values. In other words, the values can be retrieved using their corresponding keys.

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.

For example :

dictionary ={‘monday’:1, ‘tuesday’:2, ‘wednesday’:3}

The output after inverting the dictionary is { 1: [‘monday’] , 2: [‘tuesday’] , 3: [‘wednesday’] }

Given a dictionary, and the task is to invert the given dictionary.

Examples:

Example1:

Input:

Given dictionary = {10: 'jan', 20: 'feb', 30: 'march', 40: 'April', 50: 'may'}

Output:

The inverse of the given dictionary =  {'jan': [10], 'feb': [20], 'march': [30], 'April': [40], 'may': [50]}

Example 2:

Input:

Given dictionary = {'monday': 1, 'tuesday': 2, 'wednesday': 3}

Output:

The inverse of the given dictionary = {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Program to invert a Dictionary in Python

Below are the ways to invert a given dictionary

Method #1: Using For Loop (Static Input)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'monday': 1, 'tuesday': 2, 'wednesday': 3}
# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

The inverse of the given dictionary =  {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Method #2: Using For Loop (User Input)

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

Enter some random number of keys of the dictionary = 5
Enter key and value separated by spaces = hello 785
Enter key and value separated by spaces = this 100
Enter key and value separated by spaces = is 900
Enter key and value separated by spaces = btechgeeks 500
Enter key and value separated by spaces = python 400
The inverse of the given dictionary = {'785': ['hello'], '100': ['this'], '900': ['is'], '500': ['btechgeeks'], '400': ['python']}

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Numpy identity function – Python NumPy identity() Function

Python NumPy identity() Function

NumPy identity() Function:

Numpy identity function: The identity array is returned by the NumPy identity() function. The identity array is a square array with the major diagonal filled with ones.

Syntax:

numpy.identity(n, dtype=None)

Parameters

n: This is required. It represents the number of rows (and columns) in n x n output.

dtype: This is optional. It is the data type of the output. Float is the default value.

Return Value:

An n x n array with one as the main diagonal and all other entries set to 0 is returned.

NumPy identity() Function in Python

Example

Approach:

  • Import numpy module using the import keyword.
  • Pass some random number(n) as an argument to the identity() function to create an n x n array with the main diagonal set to 1 and all other entries set to 0 and store it in a variable.
  • Print the above obtained first array.
  • Pass some random number(n), datatype as int as an argument to the identity() function to create an n x n array with the main diagonal set to 1 and all other entries set to 0 (integer format) and store it in another variable.
  • Print the above obtained second array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random number(n) as an argument to the identity() function to
# create an n x n array with the main diagonal set to 1 and all other entries set to 0
# and store it in a variable.
gvn_arry1 = np.identity(3)
# Print the above obtained first array.
print("The above obtained first array = \n", gvn_arry1)

# Pass some random number(n), datatype as int as an argument to the identity() function to
# create an n x n array with the main diagonal set to 1 and all other entries set to 0
# (integer format)and store it in another variable.
gvn_arry2 = np.identity(4, dtype=int)
# Print the above obtained second array.
print("The above obtained second array = \n", gvn_arry2)

Output:

The above obtained first array = 
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
The above obtained second array = 
[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]

Example2

Here we give the datatype as the float.

# Import numpy module using the import keyword
import numpy as np
# Pass some random number(n) as an argument to the identity() function to
# create an n x n array with the main diagonal set to 1 and all other entries set to 0
# and store it in a variable.
gvn_arry1 = np.identity(3)
# Print the above obtained first array.
print("The above obtained first array = \n", gvn_arry1)

# Pass some random number(n), datatype as float as an argument to the identity() function to
# create an n x n array with the main diagonal set to 1 and all other entries set to 0
# (floating format)and store it in another variable.
gvn_arry2 = np.identity(4, dtype=float)
# Print the above obtained second array.
print("The above obtained second array = \n", gvn_arry2)

Output:

The above obtained first array = 
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
The above obtained second array = 
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

Numpy inverse tangent – Python NumPy arctan() Function

Python NumPy arctan() Function

NumPy arctan() Function:

Numpy inverse tangent: The arctan() function of the NumPy module is used to calculate the inverse tangent (arc tangent) value of a given value. The value returned will be in the range -𝜋/2 to 𝜋/2.

Syntax:

numpy.arctan(x, out=None)

Parameters

x: This is required. It is an array (array-like) having elements for which the arc tanget value is calculated.

out: This is optional. It is the location where the result will be saved. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.

Return Value: 

The arc tangent/inverse tangent value of each element of x is returned.

NumPy arctan() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Convert the above-given array angles into radians using the pi/180 of numpy module.
  • Store it in the same variable.
  • Pass the above radian angles array to the tan() function of the numpy module to get the tangent values of the given array angles.
  • Store it in another variable.
  • Pass the above tangent values array to the arctan() function of the numpy module to get the arc tangent(inverse tangent) values of the given array.
  • Store it in another variable.
  • Print the given array’s angles tangent values.
  • Print the given array’s angles inverse tangent values in radians.
  • Print the given array’s angles inverse tangent values in degrees by passing the above inverse tangent values to the degrees() function.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([30, 45, 120, 180])
# Convert the above given array angles into radians using the pi/180 of 
# numpy module.
# Store it in the same variable.
gvn_arry = gvn_arry*np.pi/180
# Pass the above radian angles array to the tan() function of the 
# numpy module to get the tangent values of the given array angles
# Store it in another variable.
tangent_arry = np.tan(gvn_arry)
# Pass the above tangent values array to the arctan() function of the 
# numpy module to get the arc tangent values of the given array
inversetan_arry = np.arctan(tangent_arry)
# Print the given array's angles tangent values
print("The given array's angles tangent values:")
print(tangent_arry)
print()
# Print the given array's angles inverse tangent values in radians
print("The given array's angles inverse tangent values in radians:")
print(inversetan_arry)
print()
# Print the given array's angles inverse tangent values in degrees by 
# passing the above inverse tangent values to the degrees() function.
print("The given array's angles inverse tangent values in degrees:")
print(np.degrees(inversetan_arry))

Output:

The given array's angles tangent values:
[ 5.77350269e-01 1.00000000e+00 -1.73205081e+00 -1.22464680e-16]

The given array's angles inverse tangent values in radians:
[ 5.23598776e-01 7.85398163e-01 -1.04719755e+00 -1.22464680e-16]

The given array's angles inverse tangent values in degrees:
[ 3.0000000e+01 4.5000000e+01 -6.0000000e+01 -7.0167093e-15]

Example2

Approach:

  • Import numpy module using the import keyword.
  • Give the array as static input and store it in a variable.
  • Print the above-given array.
  • Pass the above-given array as an argument to the arctan() function of the numpy module to get the arc tangent(inverse tangent) values of given array elements.
  • Store it in another variable.
  • Print the arc tangent(inverse tangent) values of given array elements.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Give the array as static input and store it in a variable
gvn_arry = [1, 0.5, -0.2]                   
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array as an argument to the arctan() function of the 
# numpy module to get the arc tangent(inverse tangent) values of 
# given array elements
# Store it in another variable.
inversetan_arry = np.arctan(gvn_arry)   
# Print the arc tangent(inverse tangent) values of given array elements
print("The inverse tangent values of given array elements:")
print(inversetan_arry)

Output:

The above given array is:
[1, 0.5, -0.2]
The inverse tangent values of given array elements:
[ 0.78539816 0.46364761 -0.19739556]

 

 

 

 

Replace multiple characters python – Python: Replace multiple characters in a string

How to replace multiple characters in a string in Python ?

Replace multiple characters python: In this article we will discuss about different ways to replace multiple characters in a string.

Suppose we have a String variable named my_string. So let’s see how we can replace its letters.

my_string = "You are studying from BTech Geek"

Now, we want to replace 3 characters of it i.e

  • ‘u’ will be replaced with ‘w’
  • ‘s’ will be replaced with ‘p’
  • ‘t’ will be replaced with ‘z’

Method-1 : Replacing multiple characters in a string using the replace() method

Replace multiple characters python: In python, the String class provides an inbuilt method replace()  which can be used to replace old character to new character. It replaces all occurrences of that character.

For example if we want to replace ‘a’ in a string to ‘b’ then at all the positions where ‘a’ is present those positions will be replaced with ‘b’ in the string.

Syntax : string_var_name.replace(old char, new char)

Now let’s see the implementation of it.

#Program :

#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
for key, value in char_to_replace.items():
    # Replacing matched key character with value character in string
    my_string = my_string.replace(key, value)
print(my_string)
Output :
Yow are pzwdying from BTech Geek

Method-2 : Replace multiple characters in a string using the translate ()

Replacing multiple characters in a string python: In python, the String class also provides an inbuilt method translate()  which can also be used like replace() to replace old character to new character. It replaces all occurrences of that character.

#Program :

#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
for key, value in char_to_replace.items():
    # Replacing matched key character with value character in string
    my_string = my_string.translate(str.maketrans(char_to_replace))
print(my_string)
Output : 
Yow are pzwdying from BTech Geek

Method-3 : Replacing multiple characters in a string using regex

regex module (re) in python provides a function sub() with the help of which we can also replace multiple characters of the string. Just we need to pass the pattern that we want to string.

#Program :

import re
#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
for key, value in char_to_replace.items():
    # Replacing characeters
    my_string = re.sub("[ust]",
                       lambda x: char_to_replace[x.group(0)],
                       my_string)
print(my_string)
Output : 
Yow are pzwdying from BTech Geek

Method-4 : Replacing multiple characters in a string using for loop

Python replace multiple characters: We can also replace multiple string in a string using for loop. It will iterate over the string character by6 character. When a matching character is found then it will replace the character with new character and will add to the string. If no replacement is found for that character then it ill add the character to the string.

For this we have to take a new string variable as the newly created string will stored in that new string variable.

Let’s see the implementation of it.

#Program :

#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
result_str = ''
# Iterating over all characters in string
for element in my_string:
    # Checking if character is in dict as key
    if element in char_to_replace:
        # If yes then it add the value of that char from dict to the new string
        result_str += char_to_replace[element]
    else:
        # If not then add the character in new string
        result_str += element
print(result_str)
Output : 
Yow are pzwdying from BTech Geek

Python csv writer append – Python: How to append a new row to an existing csv file?

Python-How to append a new row to an existing csv file

Python csv writer append: This tutorial will help you learn how to append a new row to an existing CSV file using some CSV modules like reader/writer and the most famous DictReader/DictWriter classes. Moreover, you can also get enough knowledge on all python concepts by visiting our provided tutorials.

How to Append a new row to an existing csv file?

Python append to csv: There are multiple ways in Python by which we can append rows into the CSV file. But here we will discuss two effective methods. Before going to learn those two methods, we have to follow the standard step which is explained ahead.

The basic step to proceed in this is to have a CSV file. For instance, here we have a CSV file named students.csv having the following contents:

Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning

For reading and writing CSV files python provides a CSV module. There are two different classes for writing CSV files that is writer and DictWriter.

We can append the rows in a CSV file by either of them but some solutions are better than the other. We will see it in the next section.

Do Refer:

Append a list as a new row to an old CSV file using csv.writer()

Append csv python: A writer class is in the CSV module which writes the rows in existing CSV files.

Let’s take a list of strings:

# List of strings
row_contents = [32,'Shaun','Java','Tokyo','Morning']

To add this list to an existing CSV file, we have to follow certain steps:

  • Import CSV module’s writer class.
  • Open our csv file in append mode and create a file object.
  • Pass this file object to the csv.writer(), we can get a writer class object.
  • This writer object has a function writerow(), pass the list to it and it will add the list’s contents as a new row in the associated csv file.
  • A new row is added in the csv file, now close the file object.

By following the above steps, the list will be appended as a row in the CSV file as it is a simple process.

from csv import writer

def append_list_as_row(file_name, list_of_elem):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)

Another Code:

Append a list as new row to an old csv file using csv.writer()

We can see that the list has been added.

Appending a row to csv with missing entries?

Python csv append: Suppose we have a list that does not contain all the values and we have to append it into the CSV file.

Suppose the list is:

list = [33, ‘Sahil’, ‘Morning’]

Example:

# A list with missing entries
row_contents = [33, 'Sahil', 'Morning']
# Appending a row to csv with missing entries
append_list_as_row('students.csv', row_contents)

some entries are missing in the list

Output:

output of missing files

We can see the data get appended at the wrong positions as the session got appended at the course.

csv’s writer class has no functionality to check if any of the intermediate column values are missing in the list or if they are in the correct order. It will just add the items in the list as column values of the last row in sequential order.

Therefore while adding a list as a row using csv.writer() we need to make sure that all elements are provided and are in the correct order.

If any element is missing like in the above example, then we should pass empty strings in the list like this,

row_contents = [33, 'Sahil', '' , '', 'Morning']

Since we have a huge amount of data in the CSV file, adding the empty strings in all of that will be a hectic task.

To save us from hectic work, the CSV provided us with the DictWriter class.

Append a dictionary as a row to an existing csv file using DictWriter in python

CSV append python: As the name suggests, we can append a dictionary as a row to an existing CSV file using DictWriter in Python. Let’s see how we can use them.

Suppose, we have a dictionary-like below,

{'Id': 81,'Name': 'Sachin','Course':'Maths','City':'Mumbai','Session':'Evening'}

We can see that the keys are the columns of the CSV and the values will be the ones we will provide.

To append it, we have to follow some steps given below:

  • import csv module’s DictWriter class,
  • Open our csv file in append mode and create a file object,
  • Pass the file object & a list of csv column names to the csv.DictWriter(), we can get a DictWriter class object
  • This DictWriter object has a function writerow() that accepts a dictionary. pass our dictionary to this function, it adds them as a new row in the associated csv file,
  • A new line is added in the csv file, now close the file object,

The above steps will append our dictionary as a new row in the csv. To make our life easier, we have created a separate function that performs the above steps,

Code:

from csv import DictWriter
def append_dict_as_row(file_name, dict_of_elem, field_names):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        dict_writer = DictWriter(write_obj, fieldnames=field_names)
        # Add dictionary as wor in the csv
        dict_writer.writerow(dict_of_elem)

Append a dictionary as a row to an existing csv file using DictWriter in python

Output:

output of appending the dict

We can see that it added the row successfully. We can also consider this thought that what if our dictionary will have any missing entries? Or the items are in a different order?

The advantage of using DictWriter is that it will automatically handle the sort of things and columns with missing entries will remain empty. Let’s check an example:

field_names = ['Id','Name','Course','City','Session']
row_dict = {'Id': 81,'Name': 'Sachin','Course':'Maths','City':'Mumbai','Session':'Evening'}
# Append a dict as a row in csv file
append_dict_as_row('students.csv', row_dict, field_names)

Output:

column with missing entries will remain empty

We can see this module has its wonders.

Hope this article was useful and informative for you.

Append to empty numpy array – Python : Create an Empty 2D Numpy Array and Append Rows or Columns to it

Create an empty 2-D NumPy array and append rows and columns

Append to empty numpy array: In this article, we will discuss what is a NumPy array, how to create a NumPy array in python, and how to append rows and columns to the empty NumPy array. First, let see what a NumPy array is and how we can create it. You can also create empty numpy array

NumPy

Numpy create empty array and append: NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it in our program and then we can easily use the functionality of NumPy in our program. Let us see how NumPy works with the help of an example.

import numpy as np

#0-D array
arr = np.array(1)
print(arr)
print(type(arr))
print()

#1-D array
arr_1d = np.array([1, 2, 3, 4, 5])
print(arr_1d)
print(type(arr_1d))
print()

#2-D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)
print(type(arr_2d))

Output

1
<class 'numpy.ndarray'>

[1 2 3 4 5]
<class 'numpy.ndarray'>

[[1 2 3]
 [4 5 6]]
<class 'numpy.ndarray'>

Here we see how we can easily work with an n-dimensional array in python using NumPy.

Let us come to the main topic of the article i.e how to create an empty 2-D array and append rows and columns to it.

Create an empty NumPy array

Create empty numpy array and append: To create an empty array there is an inbuilt function in NumPy through which we can easily create an empty array. The function here we are talking about is the .empty() function.

Syntax: numpy.empty(shape, dtype=float, order=‘C’)

It accepts shape and data type as arguments. Then returns a new array of given shapes and data types. Let us understand this with the help of an example.

array = np.empty((0, 4), int)
print(array)
print(type(array))

Output

[]
<class 'numpy.ndarray'>

This is the NumPy array consisting of 0 rows and 4 columns.

Now we understand how to create an empty 2-D NumPy array, now let us see how to append rows and columns to this empty array.

As we want to append rows and columns so there is also an inbuilt functioning NumPy to done this task and the method name is .append().

Syntax: numpy.append(arr, values, axis=None)

It contains 3 parameters. First is arr in which we have to pass our NumPy array, second is values i.e. what values we want to be appended in our NumPy array and 3rd is the axis. Axis along which values need to be appended. To append as row axis is 0, whereas to append as column it is 1.

Append rows to empty NumPy array

Numpy empty array append: With the help of the append() method, we can be done this task but we need to take care of some points before using the append function.

  1.  As we append data row-wise so we need to pass axis=0.
  2. We have to pass the row to be appended as the same shape of the numpy array otherwise we can get an error i.e. as we have created an empty array with 4 columns so now we are restricted to use 4 elements in our NumPy array otherwise we will get an error.

Let us see how this function works with the help of an example.

array = np.empty((0, 4), int)
array = np.append(array, np.array([[1,2,3,4], [5,6,7,8]]), axis=0)
print(array)
type(array)

Output

[[1 2 3 4]
 [5 6 7 8]]
numpy.ndarray

Here we see with the help of append() we easily append rows in our empty 2-D NumPy array.

Append columns to empty NumPy array

Empty 2d array python: With the help of the append() method, we can be done this task but here also we need to take care of some points before using the append function.

  1.  As we append data column-wise so we need to pass axis=1.
  2. We have to pass the column to be appended as the same shape of the numpy array otherwise we can get an error.

Let us see how this function works with the help of an example.

# Create an empty 2D numpy array with 4 rows and 0 column
array = np.empty((4, 0), int)

columns = np.array([[1,2,3,4], [5,6,7,8]])
array = np.append(array, columns.transpose(), axis=1)
print(array)

Output

[[1 5]
 [2 6]
 [3 7]
 [4 8]]

Here we see with the help of the append method how we are able to append columns to our empty 2-D NumPy array. In this example or method, we see that we use the transpose() function. So let us understand why the transpose() function is used here.

transpose() Function

Here transpose() has the same functionality that the transpose of a matrix in mathematics. Here we see that we create our array row-wise but we want to enter them in the .append() function column-wise. Hence transpose is used to swap rows and columns.

Write a program that reads a string from the user – Python Program to Read a String from the User and Append it into a File

Program to Read a String from the User and Append it into a File

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Files in Python:

Write a program that reads a string from the user: A file is a piece of information or data that is kept in computer storage devices. You are already familiar with several types of files, such as music files, video files, and text files. Python makes it simple to manipulate these files. In general, files are classified into two types: text files and binary files. Text files are plain text, whereas binary files include binary data that can only be read by a computer.

Python file handling (also known as File I/O) is an important topic for programmers and automation testers. It is necessary to work with files to either write to or read data from them.

Furthermore, if you are not already aware, I/O operations are the most expensive procedures through which a program might fail. As a result, you should take caution while implementing file handling for reporting or any other reason. Optimizing a single file activity can contribute to the development of a high-performance application or a solid solution for automated software testing.

Given a string and file, the task is to append this string to the given file.

Program to Read a String from the User and Append it into a File

Below is the full process Read a string from the user and append it to the file.

Approach:

  • Give the string as static input and store it in a variable.
  • Give the file name as user input and store it in a variable.
  • Open the file with the given file name in append mode.
  • Write a new line character to the given file using the write() function and ‘\n’.
  • Append the given string to the given file using the write() function.
  • Close the given file using close() function.
  • To print the contents of the given file after appending the string we open the file again in read mode.
  • Print the contents of the given file using for loop
  • The exit of the program.

Below is the implementation:

#Give the string as static input and store it in a variable.
givenstring=input('Enter some random string = ')
#Enter the file name of the  file using the input() function and store it in a variable.
filename = input("Enter the first file name = ")
#In append mode, open the first file with the entered file name.
givenfile=open(filename,"a")
#Write a new line character to the given file using the write() function and '\n'.
givenfile.write("\n")
#Append the given string to the given file using the write() function.
givenfile.write(givenstring)
#Close the given file using close() function.
givenfile.close()
print('Printing the contents of the given file :')
with open(filename, 'r') as givenfile:
  #Using for loop, go over the lines in the first file.
    for fileline in givenfile:
      #print the lines
        print(fileline)

Output:

Enter some random string = btechgeeks
Enter the first file name = samplefile2.txt
Printing the contents of the given file :
hello this is

btechgeeks

Explanation:

  • A file name must be entered by the user.
  • The file is opened in append mode with the open() function.
  • The user’s string is retrieved, appended to the existing file, and the file is closed.
  • The file is opened in read mode once more.
  • We printed the contents of the given file using For loop by traversing through the lines.

Google Colab Images:

Files and Code:

Code:

Output:

Samplefile2.txt


Related Programs: