Program to get the file’s first three and last three lines

In this python file program, we will get the file’s first three and last three lines. Let’s consider we have readcontent.txt file with the below content.
We will read lines of the file with read mode with the help of the below-given steps.

				
					#readcontext.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is China.
				
			
Steps to solve the program
  1. Open the file by using open(“file name”,”r”).
  2. Where file name is the name of the file and r is the reading mode.
  3. Read the lines in the file using readlines().
  4. Use a for loop to iterate over lines in the file.
  5. Using indexing print the first 3 and last 3 lines of the file.
				
					# Open file with read mode
file=open("readcontent.txt","r")
# Read file lines in the list
linesList= file.readlines()
# Print first three lines
for i in (linesList[:3]):
    print(i)
    
# Print last three lines
for i in (linesList[-3:]):
    print(i)

				
			

Output :

Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.

Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is China.

 

append data to an existing file.

get all the email ids from a text file.

Python file program to append data to an existing file

In this python file program, we will append data to an existing file. Let’s consider we have an appendcontent.txt file with the below content. We will add a new line with append mode with the help of below-given steps.

				
					# readcontent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
				
			
Steps to solve the program
  1. Open the file by using open(“file name”,”a”).
  2. Where file name is the name of the file and a is an appending mode.
  3. Using write() add the data into the file it will not get overwritten.
  4. Close the file.
				
					# Open file with append mode
f=open("appendcontent.txt","a")
# write new line to the file
f.write("New Line : This is china")
# Close the file
f.close()
				
			

Output: Now open the readontent.txt file, then we will see the newly added line will be available.

Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
New Line : This is china

 

 

overwrite the existing file content.

get the file’s first three and last three lines.

Python : How to overwrite the existing file content

We will read the text file in write (w) mode in this Python program. Let’s consider that we have a writecontent.txt file with the content below. We will write content for this file with mode with the help of the below-given steps.

# writecontent.txt

Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.

Steps to solve the program

  1. Open the file by using open(“file_name”, “w”).
  2. Where file_name is the file’s name and w is writing mode.
  3. Using write() method write the data into the file this data will overwrite the previous data.
  4. Close the file.
# Solution 1:

content = "New Line : This is China"

# open file and provide filename and write mode as (w)
file = open("writecontent.txt", "w")
file.write(content)   # write content to file using write method
file.close()              # close the file.


# Solution 2:  write content into file using function.

def write_content(filepath, content):
    file = open(filepath, "w")
    file.write(content)
    file.close()
    
write_content("writecontent.txt", content)  

Output: Once we add the written content to the file, the existing content will be overwritten, now open the writecontent.txt file, then only the newly added line will be available.

New Line: This is china

Python: How to Read a File in Reading Mode

We will read the text file in read (r) mode in this Python program. Let’s consider we have readcontent.txt file with the below content. We will read this file content in read mode with the help of the steps below.

readcontent.txt

Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia

Steps to solve the program

  1. Open the file by using open(“filename”,”r”) function.
  2. Where filename is the name of the file and r is read mode.
  3. Read file content with read() method and store it in the data variable.
  4. Print the data.
  5. Close the file.
# open file in read mode
file = open('readcontent.txt', 'r')

# read content of the file
data = file.read()

# print file data
print(data)

# close the opened file
file.close()

Output:

Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia


Program to get all permutations of a string using a string

In this python function program, we will get all permutations of a string using a string.

Permutation:
A permutation is an arrangement of objects in a definite order. It is a way of changing or arranging the elements or objects in a linear order.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Import itertools
  2. Create a function permutations
  3. Use the def keyword to define the function.
  4. Take a string as input through the user.
  5. Convert the string to the list using list().
  6. Find the permutaions i.e. different possible combinations of characters in the list using itertools.permutations(list1).
  7. Convert the result back to the list using the list.
    return the output.
  8. Call the function to get the output.
				
					import itertools
def permutations():
    string = input("Enter string: ")
    list1 = list(string)
    permutations = list(itertools.permutations(list1))
    return permutations
permutations()
				
			

Output :

				
					Enter string: name
[('n', 'a', 'm', 'e'),
 ('n', 'a', 'e', 'm'),
 ('n', 'm', 'a', 'e'),
 ('n', 'm', 'e', 'a'),
 ('n', 'e', 'a', 'm'),
 ('n', 'e', 'm', 'a'),
 ('a', 'n', 'm', 'e'),
 ('a', 'n', 'e', 'm'),
 ('a', 'm', 'n', 'e'),
 ('a', 'm', 'e', 'n'),
 ('a', 'e', 'n', 'm'),
 ('a', 'e', 'm', 'n'),
 ('m', 'n', 'a', 'e'),
 ('m', 'n', 'e', 'a'),
 ('m', 'a', 'n', 'e'),
 ('m', 'a', 'e', 'n'),
 ('m', 'e', 'n', 'a'),
 ('m', 'e', 'a', 'n'),
 ('e', 'n', 'a', 'm'),
 ('e', 'n', 'm', 'a'),
 ('e', 'a', 'n', 'm'),
 ('e', 'a', 'm', 'n'),
 ('e', 'm', 'n', 'a'),
 ('e', 'm', 'a', 'n')]
				
			

Related Articles

convert an integer to its word format.

Program to convert an integer to its word format

In this python function program, we will create a function to convert an integer to its word format.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Create a function to_number.
  2. Use the def keyword to define the function.
  3. Take a number as input.
  4. User for loop to iterate over a number after converting it into a string using str() and create an empty string.
  5. Add the words with respect to the number to the empty string.
  6. Use if-elif statements for the purpose.
  7. Print the new string which contains numbers in the word form.
  8. Call the function to get the output.
				
					def to_number():
    num = int(input("Enter a number: "))
    str1 = ""

    for i in str(num):
        if i == "1":
            str1 += "One"
        elif i == "2":
            str1 += "Two"
        elif i == "3":
            str1 += "Three"
        elif i == "4":
            str1 += "Four"
        elif i == "5":
            str1 += "Five"
        elif i == "6":
            str1 += "Six"
        elif i == "7":
            str1 += "Seven"
        elif i == "8":
            str1 += "Eight"
        elif i == "9":
            str1 += "Nine"

    print(str1)
to_number()
				
			

Output :

				
					Enter a number: 2563
TwoFiveSixThree
				
			

Related Articles

get a valid mobile number.

get all permutations from a string.

Program to get a valid mobile number using a function

In this python function program, we will get a valid mobile number using a function. A mobile number should have only 10 integers to be a valid mobile number.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Create a function mobile_number.
  2. Use the def keyword to define the function.
  3. Take the mobile number as input through the user.
  4. If the length of the number is 10 then it is a valid mobile number if not then it is not a valid number.
  5. Use an if-else statement for this purpose.
  6. Print the respective output.
  7. Call the function to get the result.
				
					def mobile_number():
    num = int(input("Enter phone number: "))
    if len(str(num)) == 10:
        print("It is a valid phone number")
    else:
        print("It is not a valid phone number")
mobile_number()
				
			

Output :

				
					Enter phone number: 24568526
It is not a valid phone number
				
			

Related Articles

get the length of the last word in a string.

convert an integer to its word format.

Program to get the length of the last word in a string using a function

In this python function program, we will get the length of the last word in a string using a function. Length means total number of characters/integers present in the word/number.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Create a function length.
  2. Use the def keyword to define the function.
  3. Take a string as input through the user.
  4. Convert the string into a list by splitting the string using split(” “).
  5. Get the length of the last word using the indexing and len() function.
  6. Print the output.
  7. Call the function to get the output.
				
					def length():
    str1 = input("Enter string: ")
    l = str1.split(" ")
    print(f"Length of the last word {l[-1]} in the string: ",len(l[-1]))
length()
				
			

Output :

				
					Enter string: sqatools in best for learning python
Length of the last word python in the string:  6
				
			

Related Articles

search words in a string.

get a valid mobile number.

Program to search words in a string using a function

In this python function program, we will search words in a string using a function.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Create a function search.
  2. Use the def keyword to define the function.
  3. Take a string and a word as input through the user.
  4. Create a count variable and assign its value equal to 0.
  5. Use a for loop to iterate over the words in the string after splitting it using split(” “).
  6. Use an if statement to check whether the word is in the string or not.
  7. If yes then add 1 to the count variable.
  8. Based on the value of the count variable and using an if-else statement determine whether the word is in the string or not.
  9. Print the respective output.
  10. Call the function to get the output.
				
					def search():
    str1 = input("Enter string: ")
    str2 = input("Enter word: ")
    count = 0
    for word in str1.split(" "):
        if word == str2:
            count += 1
    if count > 0:
        print(f"{str2} is in {str1}")
    else:
        print(f"{str2} is not in {str1}") 
search()
				
			

Output :

				
					Enter string: python programming
Enter word: python
python is in python programming
				
			

Related Articles

add two Binary numbers.

get the length of the last word in a string.

Program to add two Binary numbers using a function

In this python function program, we will add two Binary numbers using a function.

Binary Number: A number system where a number is represented by using only two digits (0 and 1) with a base 2 is called a binary number system.

Steps to solve the program
  1. Create a function binary.
  2. Use the def keyword to define the function.
  3. Pass two parameters i.e. binary numbers.
  4. Covert the binary numbers to the integers and then add them.
  5. Convert the addition to the binary number using bin().
  6. To remove the starting 0b from the number using indexing.
  7. Print the output.
  8. Pass the binary numbers to the function while calling the function.
				
					def binary(n1,n2):
    result = bin(int(n1,2)+int(n2,2))
    print(f"Addition of binary numbers {n1},{n2}: ",result[2:]) #to get rid of 0b
binary('100010','101001')
				
			

Output :

				
					Addition of binary numbers 100010,101001:  1001011
				
			

Related Articles

create a library management system.

search words in a string.