Program to extract characters from a text file into a list

In this python file program, we will extract characters from a text file into a list 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. Where the file name is the name of the file.
  3. Read the data and split it into words using file.read().split().
  4. Create an empty list to store the characters in the file.
  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. Add the characters to the list using append().
  8. Print the output.
				
					# Open file in read mode
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Create an empty list
list1 = []
# Iterate over words
for word in words:
# Iterate over Characters of the words
    for char in word:
    # Extract characters to the list
        list1.append(char)
# Print output
print("Characters in the file in the list: ",list1)
				
			

Output :

Characters in the file in the list: [‘L’, ‘i’, ‘n’, ‘e’, ‘1’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘I’, ‘n’, ‘d’, ‘i’, ‘a’, ‘.’, ‘L’, ‘i’, ‘n’, ‘e’, ‘2’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘A’, ‘m’, ‘e’, ‘r’, ‘i’, ‘c’, ‘a’, ‘.’, ‘L’, ‘i’, ‘n’, ‘e’, ‘3’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘C’, ‘a’, ‘n’, ‘a’, ‘d’, ‘a’, ‘.’, ‘L’, ‘i’, ‘n’, ‘e’, ‘4’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘A’, ‘u’, ‘s’, ‘t’, ‘r’, ‘a’, ‘l’, ‘i’, ‘a’, ‘.’, ‘L’, ‘i’, ‘n’, ‘e’, ‘5’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘A’, ‘f’, ‘r’, ‘i’, ‘c’, ‘a’, ‘.’, ‘L’, ‘i’, ‘n’, ‘e’, ‘6’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘K’, ‘o’, ‘r’, ‘e’, ‘a’, ‘.’, ‘L’, ‘i’, ‘n’, ‘e’, ‘7’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘G’, ‘e’, ‘r’, ‘m’, ‘a’, ‘n’, ‘y’, ‘.’, ‘L’, ‘i’, ‘n’, ‘e’, ‘8’, ‘:’, ‘T’, ‘h’, ‘i’, ‘s’, ‘i’, ‘s’, ‘C’, ‘h’, ‘i’, ‘n’, ‘a’, ‘.’]

 

 

check whether a file is closed or not.

read the data of two of the files created and add it to a new file.

Leave a Comment