Program to get odd lines from files and append them to separate files

In this python file program, we will get odd lines from files and append them to separate files. Let’s consider we have readcontent.txt file with the below content. We will get odd lines from files and append them to separate files with the help of the below-given steps.

				
					Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
Line9 : This is Australia.
Line10 : This is Zimbabwe.
Line11 : This is Nederland.
Line12 : This is scotland.
Line13 : This is Japan.
				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt“,”r”).
  2. Read the lines in the file using readlines().
  3. Now open the second file by using open(“writecontent.txt“,”w”).
  4. Where file name is the name of the file and w is writing mode.
  5. Use a for loop with the range function to iterate over the lines in the first file.
  6. If the line number is not divisible by 2 then add that line to the second file using write().
  7. Close the file.
				
					# Open 1st file in read mode
f1 = open('readcontent.txt', 'r')
# Open 2nd file in write mode
f2 = open('writecontent.txt', 'w')
# Read lines of the file  
lines_list = f1.readlines()
# Iterate over lines
for i in range(0, len(lines_list)):
# Check for odd line
    if((i+1) % 2!= 0):
    # Write lines to 2nd file
        f2.write(lines_list[i])
    else:
        pass
# Close the file  
f1.close()
f2.close()
				
			

Output: Now open the writecontent.txt file to see the odd lines from the readcontent.txt file.

Line1 : This is India.
Line3 : This is Canada.
Line5 : This is Africa.
Line7 : This is Germany.
Line9 : This is Australia.
Line11 : This is Nederland.
Line13 : This is Japan.

 

 

get a specific line from the file.

read a file line by line and store it in a list.

Python program to get a specific line from the file

In this python file program, we will get a specific line from the file. Let’s consider we have readcontent.txt file with the below content. We will get a specific line from the file with the help of the 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(“readcontent.txt,”r“).
  2. Where the file name is the name of the file.
  3. Read the lines in the file using readlines().
  4. Print the 1st line of the file by using indexing.
  5. Close the file.
				
					# Open the file
file = open("readcontent.txt","r")
# Read lines of the file
data = file.readlines()
# Print 1st line
print("1st line")
print(data[0])
# Close the file
file.close()
				
			

Output : 
1st line
Line1 : This is India.

get all the email ids from a text file.

get odd lines from files and append them to separate files.

Program to get all the email ids from a text file

In this python file program, we will get all the email ids from a text file. Let’s consider we have ReadContentEmail.txt file with the below content.
We will get the email ids from the file with the help of the below-given steps.

				
					Line1 : This is India.
Line2 : This is America.
Line3 : This test1@gmail.com first email.
Line4 : This is Australia.
Line5 : This test2@gmail.com first email.
Line6 : This is Korea.
Line7 : This test3@gmail.com first email.
Line8 : This is China.
				
			
Steps to solve the program
  1. Create an empty list to store the email ids.
  2. Open the file by using open(“ReadContentEmail.txt”,”r”).
  3. Read the file using read() and store the data in a variable.
  4. Now split the data to convert it into words using split() and store the result in a variable.
  5. Use a for loop to iterate over words.
  6. Use an if-else statement to check whether the word contains in it.
  7. If yes then add it to the empty list, else continue the loop.
  8. After for loop is complete print the list of email ids.
  9. Close the file.
				
					# Create an empty list
email_list = []
# Open the file in reading mods
file = open("ReadContentEmail.txt", "r")
# Read the data in the file
file_data = file.read()
# Convert the data into words
word_list = file_data.split(" ")
# Iterate over the words
for word in word_list:
# Check for @ in the word
    if "@" in word:
    # Add word to the empty list
        email_list.append(word)
    else:
        continue
# Print output
print(email_list)
# Close the file
file.close()
				
			

Output : 

				
					['test1@gmail.com', 'test2@gmail.com', 'test3@gmail.com']
				
			

 

 

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

get a specific line from the file.

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.