Python file program to get the size of a file

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

				
					#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 the os library.
  2. Open the file using os.stat(‘readcontent’) and store the output in the variable.
  3. Get the size of the file using info.st_size.
  4. Print the output.
				
					# Import os library
import os
# Read file
info = os.stat('readcontent.txt')
# Print size of the file
print("Size of the file: ",info.st_size)
				
			

Output:

Size of the file: 193

 

 

count the number of lines in a file.

write a tuple to a file.

Program to count the number of lines in a file

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

				
					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. Open the first file by using open(“readcontent.txt”,”r”).
  2. Read the lines in the file using readlines().
  3. Create a count variable and assign its value equal to 0.
  4. Use a for loop to iterate over lines in the file.
  5. After each iteration add 1 to the count variable.
  6. Print the output.
				
					# Open file in read mode
file=open("readcontent.txt","r")
# Read lines
lines= file.readlines()
# Create count variable
count = 0
# Iterate over lines
for line in lines:
# Add 1 to count for each line
    count += 1
# Print output
print("Total number of lines in the file: ",count)
				
			

Output : 

Total number of lines in the file: 8


compare two files.

get the file size of a file.

Python file program to compare two files

In this python file program, we will compare two files with the help of the below-given steps.. Let’s consider we have file1.txt and file2.txt files with the below content.

				
					#file1.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.

#file2.txt
Jay - 3569872214
Yash - 9865472589
Ketan - 8854632255
Rajesh - 7020589634
				
			
Steps to solve the program
				
					# Impoer difflib library
import difflib 
# Open file and read lines
with open('file1.txt') as file_1:
# Open file and read lines
    file_1_text = file_1.readlines() 
with open('file2.txt') as file_2:
    file_2_text = file_2.readlines()
for line in difflib.unified_diff(
        file_1_text, file_2_text, fromfile='file name',
        tofile='file.txt', lineterm=''):
    print(line)
				
			

Output :

--- file1.txt
+++ file2.txt
@@ -1,8 +1,4 @@
-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.
+Jay - 3569872214

+Yash - 9865472589

+Ketan - 8854632255

+Rajesh - 7020589634

count the number of lines in a file.

Program to get all mobile numbers from a file

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

				
					Jay - 3569872214
Yash - 9865472589
Ketan - 8854632255
Rajesh - 7020589634
				
			
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 an empty list to store the mobile number.
  4. Use a for loop to iterate over words.
  5. Check whether the word is a number or not using isnumeric().
  6. If yes then check whether the length of the number is 10 or not.
  7. If yes then add it to the empty list.
  8. Print the output.
				
					# Open the file
file = open('readcontent.txt')
# Read data and converting it to words
data = file.read().split()
# Create an empty list
m_num = []
# Iterate over words
for val in data:
# Check whether a word in a numeric
    if val.isnumeric():
    # Check for mobile number
        if len(val) == 10:
    # Add number to the list
            m_num.append(val)
# Print output
print("Mobile numbers in the file: ",m_num)
				
			

Output :

Mobile numbers in the file: [‘3569872214’, ‘9865472589’, ‘8854632255’, ‘7020589634’]

 

 

get all odd and even length words in two lists.

Python file program to get all odd and even length words in two lists

In this python file program, we will get all odd and even length words in two lists with the help of the below-given steps.. Let’s consider we have readcontent.txt file with the below content.

				
					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. Open the first file by using open(“readcontent.txt”).
  2. Read the data and split it into words using file.read().split().
  3. Create two empty lists even and odd.
  4. Use a for loop to iterate over the words.
  5. If the length of the word is even then add it to the even list, else add it to the odd list.
  6. Use an if-else statement for this purpose.
  7. Print the output.
				
					# Open the file
file = open('readcontent.txt')
# Convert data into words
words = file.read().split()
# Create empty lists
even = []
odd = []
# Iterate over words
for word in words:
# Check for odd,even words
# Add them to corresponding list
    if len(word)%2==0:
        even.append(word)
    else:
        odd.append(word)
# Print output
print("Words having even length: ",even)
print("Words having odd length: ",odd)
				
			

Output :

Words having even length:
[‘This’, ‘is’, ‘India.’, ‘This’, ‘is’, ‘America.’, ‘This’, ‘is’, ‘This’, ‘is’, ‘Australia.’, ‘This’, ‘is’, ‘This’, ‘is’, ‘Korea.’, ‘This’, ‘is’, ‘Germany.’, ‘This’, ‘is’, ‘China.’]

Words having odd length:
[‘Line1’, ‘:’, ‘Line2’, ‘:’, ‘Line3’, ‘:’, ‘Canada.’, ‘Line4’, ‘:’, ‘Line5’, ‘:’, ‘Africa.’, ‘Line6’, ‘:’, ‘Line7’, ‘:’, ‘Line8’, ‘:’]

 

 

generate text files with all alphabets.  e.g. A.txt , B.txt, C.txt….. Z.txt

get all mobile numbers from a file.

Program to generate text files with all alphabets names

In this python file program, we will generate text files with all alphabets names. In this program, there is no file to take as input because we will generate the files having all alphabets names.

Steps to solve the program
				
					# Import os,string library
import string, os
# Check if the files with the alphabet names exists or not
if not os.path.exists("letters"):
# If not then make a new file
   os.makedirs("letters")
# Iterate over letters in the alphabets
for letter in string.ascii_uppercase:
# Open the files with write mode
   with open(letter + ".txt", "w") as f:
   # Add corresponding letter to the file
       f.writelines(letter)
				
			

Output :

A.txt
B.txt
C.txt
D.txt
.
.
.
.
.
.
X.txt
Y.txt
Z.txt

 

 

get all odd and even length words in two lists.

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.