Sort Lines of File with Python

Sort lines of file with Python is an easy way to arrange the file content in ascending order. In this article, we will focus to sort lines of file with the length of each line and sorting the lines in Alphabetical order.

Sort lines of file with line length size:

Let’s consider a text with the name sortcontent.txt which
contains some lines that we will try to sort on the basis of length of the each line.
				
					# sortcontent.txt
This is Python
Hello Good Morning How Are You.
This is Java
Python is good language

				
			
Steps to solve the program
  1. Open the first file using open(“sortcontent.txt”,”r”).
  2. Read all the lines of the file using readlines() method
  3. Now compare all lines one by one and exchange place
    of long length lines with small length lines to re-arrange them
    in ascending order using a nested loop.
  4. re-write all the lines of the list in ascending order.
				
					# Open file in read mode with context manager
with open("sortcontent.txt", "r") as file:
    # Read list of lines.
    FileLines = file.readlines()
    # Initial for loop to start picking each line one by one
    for i in range(len(FileLines)):
        # Initial for loop to compare all remaining line with previous one.
        for j in range(i+1, len(FileLines)):
            # compare each line length, swap small len line with long len line.
            if len(FileLines[i]) > len(FileLines[j]):
                temp = FileLines[i]
                FileLines[i] = FileLines[j]
                FileLines[j] = temp
            else:
                continue

# re-write all the line one by one to the file
with open('ReadContent.txt', "w") as file:
    # Combine all the sequentially arrange lines with join method.
    all_lines = ''.join(FileLines)
    # overwrite all the existing lines with new one
    file.write(all_lines)
				
			

Output: Open the sortcontent.txt file to see the output. below content will be available in the file. All lines of the file will arrange in ascending as per their length.

				
					This is Java
This is Python
Python is good language
Hello Good Morning How Are You.
				
			


Sort lines of file in Alphabetical order
:

Let’s consider a text file with a city name list, where names are mentioned one name in each line In the below program will sort the line of the file in alphabetical order, reads all the names from a file, and print them in alphabetical order.

				
					# cityname.txt
Kolkata
Mumbai
Pune
Bangalore
Delhi
				
			
				
					# open file with context manager
with open('cityname.txt') as file:
    # read all lines with readlines() method.
    file_lines = file.readlines()
    # sort line of file in alphabetical order
    file_lines.sort()
    # print all sorted name using loop
    for line in file_lines:
        print(line)
				
			

When we will run above program, will get following output.

				
					Bangalore
Delhi
Kolkata
Mumbai
Pune
				
			

Related Articles

display words from a file that has less than 5 characters.

Python file program to replace space by an underscore in a file

In this python file program, we will replace space by an underscore in a file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.

				
					#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.

				
			
Steps to solve the program
  1. Open the first file using open(“readcontent.txt”,”r”).
  2. Read the data in the file using read().
  3. Replace the space in the data with “_” using replace() and store the output in the new variable.
  4. Open the second file using open(“writecontent.txt”,”w”).
  5. Write the new data in the second file using write().
				
					# Open file in read mode
f1=open("readcontent.txt","r")
# Read data
data=f1.read()
# Replace space by underscore
data=data.replace(" ","_")
# Open file in write mode
f2=open("file2.txt","w")
# Write new data to file
f2.write(data)
				
			

Output: Open the writecontent.txt file to see the ouput.

My_name_is_john.
I’m_20_years_old.
I’m_learning_python_at_sqatools.
I’m_from_Australia.

 

 

display words from a file that has less than 5 characters.

Program to display words from a file that has less than 5 characters

In this python file program, we will display words from a file that has less than 5 characters with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.

				
					#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.

				
			
Steps to solve the program
  1. Open the file by using open(“readcontent.txt”).
  2. Where the file name is the name of the file.
  3. Read the data and split it into words using file.read().split().
  4. Use a for loop to iterate over the words.
  5. If the length of the word is less than 5 then print that word.
  6. Use an if statement for this purpose.
				
					# Open the file
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Iterate over words
for word in words:
# Check for words having length less than 5
    if len(word)<5:
    # Print output
        print(word,end=" ")
				
			

Output:

My name is I’m 20 old. I’m at I’m from

 

 

remove all the lines that contain the character ‘t’ in a file and write it to another file.

replace space by an underscore in a file.

Program to count the total number of consonants in a file

In this python file program, we will count the total number of consonants in 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.

				
			
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 list of vowels.
  4. Create a count variable and assign its value equal to 0.
  5. Use a for loop to iterate over the words.
  6. Use a nested for loop to iterate over the characters in the word.
  7. Check whether the character is not in the vowels list using an if statement.
  8. If yes then add 1 to the count variable.
  9. Print the output.
				
					# Open file
file = open('readcontent.txt')
# Read data and converting into words
words = file.read().split()
# Create a list of vowels
vowels = ['a','e','i','o','u','A','E','I','O','U']
# Create count variable
count = 0
# Iterate over words
for word in words:
# Iterate over characters in the word
    for char in word:
    # Check for consonants
        if char not in vowels:
    # Add 1 to the count variable for each consonant
            count += 1
# Print output
print("Total number of consonants in the file: ",count)
				
			

Output :

Total number of consonants in the file: 48

 

 

count the total number of vowels in a file.

remove all the lines that contain the character ‘t’ in a file and write it to another file.

Program to count the total number of vowels in a file

In this python file program, we will count the total number of vowels in 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.

				
			
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 list of vowels.
  4. Create a count variable and assign its value equal to 0.
  5. Use a for loop to iterate over the words.
  6. Use a nested for loop to iterate over the characters in the word.
  7. Check whether the character is in the vowels list using an if statement.
  8. If yes then add 1 to the count variable.
  9. Print the output.
				
					# Open file
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Create list of vowels
vowels = ['a','e','i','o','u','A','E','I','O','U']
# Create count variable
count = 0
# Iterate over words
for word in words:
# Iterate over characters in the word
    for char in word:
    # Check for vowels
        if char in vowels:
    # Add 1 to the count variable for each vowel
            count += 1
# Print output
print("Total number of vowels in the file: ",count)
				
			

Output :

Total number of vowels in the file: 31

 

 

count the total number of consonants in a file.

Program to read the content of the file in reverse order

In this python file program, we will read the content of the file in reverse order 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.

				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the data in the file using read().
  3. Convert it to a list using list().
  4. Now reverse the list using reversed().
  5. Use a for loop to iterate over the lines in the reversed list and print the line.
				
					# Open file
file = open('readcontent.txt')
# Read lines and converting it to a list
data = list(file.readlines())
# Iterate over lines in reverse order
for line in reversed(data):
    print(line)
				
			

Output :

Line4 : This is Australia.

Line3 : This is Canada.

Line2 : This is America.

Line1 : This is India.




move the cursor to a specific position in a file.

Program to move the cursor to a specific position in a file

In this python file program, we will move the cursor to a specific position in 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.

				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the lines using readlines().
  3. Print the position of the cursor using file.tell()
  4. Move the cursor to the 10th position using file.seek(10).
  5. Again print the position of the cursor using file.tell().
				
					# Open the file
file = open('readcontent.txt')
# Read lines in the file
file.readline()
# Print position of the curosr
print("Position of a cursor in the file: ",file.tell())
# Move cursor to a specific Position
file.seek(10)
# Again print position of the cursor
print("Position of a cursor in the file: ",file.tell())
				
			

Output :

Position of a cursor in the file: 23 
Position of a cursor in the file: 10


 

find the cursor position in a file.

read the content of the file in reverse order.

Program to find the cursor position in a file

In this python file program, we will find the cursor position in 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.

				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the lines using readlines().
  3. Print the position of the cursor using file.tell()
				
					# Open the file
file = open('readcontent.txt')
# Read lines of the file
file.readline()
# Print the position of the cursor
print("Position of a cursor in the file: ",file.tell())
				
			

Output :

Position of a cursor in the file: 23

 

 

count the total number of special characters in a file.

move the cursor to a specific position in a file.

Program to count the total number of special characters in a file

In this python file program, we will count the total number of special characters in 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 @ndia.
Line2 : This is $America.
Line3 : This is Canada?.
Line4 : This is #Australia.

				
			
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 count variable and assign its value equal to 0.
  4. Create a list of special characters
  5. Use a for loop to iterate over the words.
  6. Use a nested for loop to iterate over the characters in the word.
  7. If the character is in the list then add 1 to the count variable.
  8. Print the output.
				
					# Open the file
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Create count variable
count = 0
# Create list of special characters
special = ['!','@','#','$','%','^','&','*',
          '~','`','?',':',';']
# Iterate over words
for word in words:
# Iterate over characters in the word
    for char in word:
    # Check for special characters
        if char in special:
    # Add 1 to the count variable for each special character
            count += 1
# Print output
print("Total number of digits in the file: ",count)
				
			

Output :

Total number of digits in the file: 8

 

 

count the total number of digits in a file.

find the cursor position in a file.

Program to count the total number of digits in a file

In this python file program, we will count the total number of digits in 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.
				
			
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 count variable and assign its value equal to 0.
  4. Use a for loop to iterate over the words.
  5. Use a nested for loop to iterate over the characters in the word.
  6. Check if the character is a number or not using isnumeric().
  7. If yes then add 1 to the count variable.
  8. Print the output.
				
					# Open the file
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Create count variable
count = 0
# Iterate over words
for word in words:
# Iterate over characters in the word
    for char in word:
    # Check for digits
        if char.isnumeric():
    # Add 1 to the count variable for each digit
            count += 1
# Print output
print("Total number of lower case characters in the file: ",count)
				
			

Output :

Total number of digits in the file: 4

 

 

count the total number of Lowercase characters in a file.

count the total number of special characters in a file.