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


Python File Handling Programs, Exercises

Python File Handling Programs refers to the process of manipulating files on a computer using Python programming language. In Python, you can perform various operations on files such as reading, writing, appending, and deleting files.

To perform file handling in Python, you first need to open a file. The open() function is used to open a file. It takes two parameters – the file name (along with the path, if necessary) and the mode in which you want to open the file.

1). Python Program How to read a file in reading mode.

2). Python file program to overwrite the existing file content.

3). Python file program to append data to an existing file.

4). Python file program to get the file’s first three and last three lines.

5). Python file program to get all the email ids from a text file.

6). Python file program to get a specific line from the file.

7). Python file program to get odd lines from files and append them to separate files.

8). Python file program to read a file line by line and store it in a list.

9). Python file program to find the longest word in a file.

10). Python file program to get the count of a specific word in a file.

11). Python file program to read a random line from a file.

12). Python file program to copy the file’s contents to another file after converting it to lowercase.

13). Python file program to copy the file’s contents to another file after converting it to uppercase.

14). Python file program to count all the words from a file.

15). Python file program to sort all the lines File as per line length size.

16). Python file program to consider a text file as a DB file and store all the student information in a text file.

17). Python file program to create n number of text files with given strings.

18). Python file program to generate text files with all alphabets.  e.g. A.txt , B.txt, C.txt….. Z.txt

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

20). Python file program to get all mobile numbers from a file. e.g each mobile number size should be 10.

21). Python file program to get a list of all domains from a file. e.g. .com, .au, .in

22). Python file program to compare two files.

23). Python file program to count the number of lines in a file.

24). Python file program to get the file size of a file.

25). Python file program to write a tuple to a file.

26). Python file program to check whether a file is closed or not.

27). Python file program to extract characters from a text file into a list.

28). Python file program to read the data of two of the files created and add it to a new file.

29). Python file program to count the total number of characters in a file.

30). Python file program to count the total number of Uppercase characters in a file.

31). Python file program to count the total number of Lowercase characters in a file.

32). Python file program to count the total number of digits in a file.

33). Python file program to count the total number of special characters in a file.

34). Python file program to find the cursor position in a file.

35). Python file program to move the cursor to a specific position in a file.

36). Python file program to read the content of the file in reverse order.

37). Python file program to read a file and display each word separated by @.

38). Python file program to count the total number of vowels in a file.

39). Python file program to count the total number of consonants in a file.

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

41). Python file program to display words from a file that has less than 5 characters.

42). Python file program to replace space by an underscore in a file.

For reference here python input/output official documentation.

Read File In Python

Method read() reads at most size bytes from the file and read hits the end of the file before obtaining size bytes, then it reads only available bytes.

read_file.txt input file

input file.txt
In the below program example, we are opening a text file with read mode, and read mode has this read method that read the entire file content from beginning to end. The open method accepts two parameters file path and file mode to open.
def read_file_content(filename):
    file = open(filename, 'r+')
    file_data = file.read()
    print(file_data)

filename = "input_file.txt"
read_file_content(filename)

Output:

output data