Python file program to count all the words from a file

In this python file program, we will count all the words from a file. Let’s consider we have readcontent.txt file with the below content. We will count all the words from a file with the help of the below-given steps.

				
					# ReadContent.txt
This is Python
This is Java
Python is good language Poetry' );
				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the data and split it into words using file.read().split().
  3. Create a variable count and assign its value equal to 0.
  4. Use for loop to iterate over words.
  5. After each iteration add 1 to the count variable.
  6. Print the total number of words in the file.
				
					# Open the file
file = open('readcontent.txt')
# Convert data to words
words = file.read().split()
# Create a count variable
count = 0
# Iterate over words
for word in words:
# Add 1 to the count variable for each word
    count += 1
# Print output
print("Count of words in the file: ",count)
				
			

Output: 

Count of words in the file: 10

 

 

copy the file’s contents to another file after converting it to uppercase.

Copy the file’s contents after converting it to uppercase

In this python file program, Let’s consider we have readcontent.txt file with the below content. We will copy the file’s contents to another file after converting it to uppercase 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.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
				
			
Steps to solve the program
  1. First, read the first file in the reading mode using with open(‘Readcontent.txt’, ‘r’) as data_file.
  2. Inside the above statement use another statement to read the second file in appending mode using with open(‘Writecontent.txt’, ‘a’) as output_file.
  3. Use a for loop to iterate over lines in the first file.
  4. Add each line to the second file by using write() after converting the characters in the line to uppercases using upper().
				
					# Open file in read mode
with open('file name', 'r') as data_file:
    # Open another file in write mode
        with open('file.txt', 'a') as output_file:
    # Iterate over lines of the file
            for line in data_file:
    # Convert characters in the line to uppercases and
    # Write it to 2nd file
                output_file.write(line.upper())
				
			

Output : Open the Writecontent.txt file to see the output

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.

 

 

copy the file’s contents to another file after converting it to lowercase.

count all the words from a file.

Program to copy the file’s contents to another file after converting it to lowercase

In this python file program, Let’s consider we have readcontent.txt file with the below content. We will copy the file’s contents to another file after converting it to lowercase 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.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
				
			
Steps to solve the program
  1. First read the first file in the reading mode using with open(‘ReadContent.txt’, ‘r’) as data_file.
  2. Inside the above statement use another statement to read the second file in appending mode using with open(‘Writecontent.txt’, ‘a’) as output_file.
  3. Use a for loop to iterate over lines in the first file.
  4. Add each line to the second file by using write() after converting the characters in the line to the lowercases using lower().
				
					# Open file in read mode
with open('ReadContent.txt', 'r') as data_file:
        # Open another file in append mode
        with open('Writecontent.txt', 'a') as output_file:
            # Iterate over lines of the file
            for line in data_file:
                # Convert characters in the line to lowercases and
                # Write it to 2nd file
                output_file.write(line.lower())
				
			

Output : Open the Writecontent.txt file to see the output

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.

 

 

read a random line from a file.

copy the file’s contents to another file after converting it to uppercase.

Python file program to read a random line from a file

In this python file program, we will read a random line from a file. Let’s consider we have readcontent.txt file with the below content. We will read a random line from a 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.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
				
			
Steps to solve the program
  1. Import re library.
  2. Open the file, read it, and split the lines using open(‘readcontnent.txt’).read().splitlines().
  3. Read a random line from the lines using random.choice(lines).
  4. Print the output.
				
					# Import random library
import random
# Read data from the file and splitting it into lines
lines = open('readcontent.txt').read().splitlines()
# Get a random line from the lines
data=random.choice(lines)
# Print output
print(data)
				
			

Output :

Line7 : This is Germany.

 

 

get the count of a specific word in a file.

copy the file’s contents to another file after converting it to lowercase.

Program to count of a specific word in a file

In this python file program, we will count of a specific word in a file. Let’s consider we have readcontent.txt file with the below content. We will get a count of a specific word in a file with the help of the below-given steps.

				
					# ReadContent.txt
This is Python Programming Language
Its very Python easy to learn to and 
Best language for Python beginners
				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”,”r”).
  2. Read the data and split it into words using file.read().split().
  3. Create a variable count and assign its value equal to 0.
  4. Use for loop to iterate over words.
  5. If the word is equal to python then add 1 to the count variable.
  6. Print the respective output.
				
					# Open file with read mode
file = open('readcontext.txt','r')
# Read the data in the file and convert it into words
words = file.read().split()
# Create count variable
count = 0
# Iterate over the words
for word in words:
# Match word
    if word == 'Python':
        count += 1
# Print output
print("Count of python in the file: ",count)
				
			

Output :

Count of Python in the file: 3

 

 

find the longest word in a file.

read a random line from a file.

Python file program to find the longest word in a file

In this python file program, we will find the longest word in a file. Let’s consider we have readcontent.txt file with the below content. We will find the longest word in a file with the help of the below-given steps.

				
					# ReadContent.txt
This is Python Programming Language
Its very easy to learn to and 
Best language for beginners
				
			
Steps to solve the program
  1. Create a varibale to store the longest word and assign ita value equal to empty string.
  2. Create another variable to store its length and assign its value equal to 0.
  3. Read the file using open(“readcontent.txt,”r“).
  4. Read the using read().
  5. Convert the data into words using split().
  6. Use a for loop to iterate over the words.
  7. Use an if-else statement to check whether the length of the word is greater than max_len.
  8. If yes then assign the length of that word to max_len and the word to max_word.
  9. After the loop is complete then print the output.
				
					# Create variables
max_word = ''
max_len = 0
# Read file with read mode
with open("ReadContent.txt", "r") as file:
    file_data = file.read()
    # Convert data into words
    word_list = file_data.split()
    # Iterate over words
    for word in word_list:
    # Check for word with maximum length
        if len(word) > max_len:
            max_len = len(word)
            max_word = word
        else:
            continue
# Print the result
print("Max length word :", max_
				
			

Output :

Max length word : Programming
Max length : 11

 

 

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

get the count of a specific word in a file.

Program to read a file line by line and store it in a list

In this python file program, we will read a file line by line and store it in a list. Let’s consider we have readcontent.txt file with the below content. We will read a file line by line 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.
Line5 : This is Africa.
				
			
Steps to solve the program
  1. Set result_list blank list variable.
  2. Open the file with context manager with read mode.
  3. Initiate an infinite while loop.
  4. Read each line one by one.
  5. Check line is black or not and break the loop if it is blank.
  6. Append the lines in the result_list.
  7. print the result_list.
				
					result_list = []
# Read file with context manager
with open("ReadContent.txt", "r") as file:
    while True:
        # read all line one by one until it is blank.
        line = file.readline()
        # once receive blank line, then break the loop
        if not line:
            break
        result_list.append(line)

    print(result_list)
				
			

Output: 

[‘Line1 : This is India.\n’, ‘Line2 : This is America.\n’, ‘Line3 : This is Canada.\n’, ‘Line4 : This is Australia.\n’, ‘Line5 : This is Africa.’]

 

 

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

find the longest word in a file.

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.