Home » Python » Python programs

Copy odd lines of one file to another file in Python

Here, we are going to learn how to copy odd lines of one file to another file in Python programming language?
Submitted by IncludeHelp, on February 14, 2020

Let suppose there is a file named "file1.txt", that contains following content,

    This is line 1.
    This is line 2.
    This is line 3.
    This is line 4.
    This is line 5.

And, we are copying odd lines to another file named "file2.txt".

Example:

    Input: "file1.txt"
    This is line 1.
    This is line 2.
    This is line 3.
    This is line 4.
    This is line 5.

    Output: "file2.txt"
    This is line 2.
    This is line 4.

Python program to copy odd lines of one file to another file

# opening the file
file1 = open('file1.txt', 'r') 

# creating another file to store odd lines
file2 = open('file2.txt', 'w') 

# reading content of the files
# and writing odd lines to another file
lines = file1.readlines() 
type(lines) 
for i in range(0, len(lines)): 
	if(i % 2 != 0): 
		file2.write(lines[i]) 

# closing the files
file1.close()
file2.close() 

# opening the files and printing their content
file1 = open('file1.txt', 'r') 
file2 = open('file2.txt', 'r') 

# reading and printing the files content
str1 = file1.read()
str2 = file2.read()

print("file1 content...")
print(str1)

print() # to print new line

print("file2 content...")
print(str2)

# closing the files
file1.close()
file2.close()

Output

file1 content...
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.

file2 content...
This is line 2.
This is line 4.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.