Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to compare two text files in python?
Next article icon

Python program to copy odd lines of one file to other

Last Updated : 06 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Program to read the contents of a file and copy only the content of odd lines into a new file. By identifying whether the line number is odd or even in Python.

Examples:

Input :             Hello             World             Python             Language  Output : Hello                 Python  Explanation: The output file has only the odd line form the input file

Copy odd lines of one file to another file in Python

Here we first open the file in read mode from which we have to read the data and open the second file in write mode in which we have to write the data. Now we initiate a for loop to integrate over the input file and check whether the line is odd or not and if the line is odd then copy the line from the file and write it in the output file.

Python3




def copy_odd_lines(input_file, output_file):
    with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
        for line_number, line in enumerate(infile, 1):
            if line_number % 2 != 0:
                outfile.write(line)
 
# Example usage:
input_file_name = 'input.txt'
output_file_name = 'output.txt'
copy_odd_lines(input_file_name, output_file_name)
 
 

Output:

Hello  Python

Note: Keep your input file in the same directory.

Python to write specific lines from one file to another file

Here we first open the file in read mode from which we have to read the data and open the second file in write mode in which we have to write the data. Now in input with the input file and output file, we also take a number of the specific lines which we need to copy from the input_file.

Python3




def copy_specific_lines(input_file, output_file, line_numbers):
    with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
        for line_number, line in enumerate(infile, 1):
            if line_number in line_numbers:
                outfile.write(line)
 
 
# Example usage:
input_file_name = 'input.txt'
output_file_name = 'output.txt'
# Put the line numbers you want to copy here
lines_to_copy = [1, 2]
copy_specific_lines(input_file_name,
                    output_file_name, lines_to_copy)
 
 

Output:

Hello  Python

Note: Keep your file in the same directory.



Next Article
How to compare two text files in python?

P

PranshuAgarwal1
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Python - Copy Files From Subfolders to the Main folder
    In this article, we will discuss how to copy a file from the subfolder to the main folder. The directory tree that will be used for explanation in this article is as shown below: D:\projects\base | |__subfolder: | \__file.txt | |__main.py | Here we have a folder named "base" in which we have a folde
    4 min read
  • Count number of lines in a text file in Python
    Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output:
    3 min read
  • How to copy file in Python3?
    Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Pyt
    2 min read
  • How to compare two text files in python?
    Python has provided the methods to manipulate files that too in a very concise manner. In this article we are going to discuss one of the applications of the Python's file handling features i.e. the comparison of files. Files in use: Text File 1Text File 2Method 1: Comparing complete file at once Py
    3 min read
  • How to Find the Longest Line from a Text File in Python
    Finding the longest line from a text file consists of comparing the lengths of each line to determine which one is the longest. This can be done efficiently using various methods in Python. In this article, we will explore three different approaches to Finding the Longest Line from a Text File in Py
    3 min read
  • Convert Text file to JSON in Python
    JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. Thi
    4 min read
  • Compare two Files line by line in Python
    In Python, there are many methods available to this comparison. In this Article, We'll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation.
    3 min read
  • How to move all files from one directory to another using Python ?
    In this article, we will see how to move all files from one directory to another directory using Python.  In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil m
    2 min read
  • file parameter of Python's print() Function
    print() function in Python3 supports a ‘file‘ argument, which specifies where the function should write a given object(s) to. If not specified explicitly, it is sys.stdout by default. It serves two essential purposes: Print to STDERRPrint to external fileNote: The 'file' parameter is found only in P
    5 min read
  • Python | Move or Copy Files and Directories
    Let's say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories. Code #1 : Using shutil module import shutil # Copy src to dst. (cp src dst) shutil.
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences