Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a file line by line in python

Tags:

python

I am writing a python program to copy a file line by line into a new file. The code I have is below in which I am using a loop to copy the file line by line.

However since the number of lines in the file may change, is there a way to copy a file line by line in python without using a loop which relies on numbers, and instead relies on the something like the EOF character to terminate the loop?

import os
import sys

i = 0
f = open("C:\\Users\\jgr208\\Desktop\\research_12\\sap\\beam_springs.$2k","r")
copy = open("C:\\Users\\jgr208\\Desktop\\research_12\\sap\\copy.$2k","wt")
#loop that copies file line by line and terminates loop when i reaches 10
while i < 10:
     line = f.readline()
     copy.write(str(line))
     i = i +1
f.close()
copy.close()
like image 544
jgr208 Avatar asked Jul 20 '12 17:07

jgr208


People also ask

How do I copy a line from one file to another in Python?

The shutil. copy() method in Python is used to copy the content of the source file to destination file or directory.

How do you split a file line by line in Python?

Example 1: Using the splitlines() the read() method reads the data from the file which is stored in the variable file_data. splitlines() method splits the data into lines and returns a list object. After printing out the list, the file is closed using the close() method.

How do you copy a file path in Python?

shutil. copy() method is used to copy specified source (without the metadata) to the destination file or directory and it will return the path to the newly created file. The src can either be a path-like object or a string.


2 Answers

You can iterate over lines in a file object in Python by iterating over the file object itself:

for line in f:
    copy.write(line)

From the docs on file objects:

An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code:

>>> for line in f:
        print line,
like image 195
Andrew Clark Avatar answered Oct 14 '22 17:10

Andrew Clark


Files can be iterated directly, without the need for an explicit call to readline:

f = open("...", "r")
copy = open("...", "w")
for line in f:
    copy.write(line)
f.close()
copy.close()
like image 38
chepner Avatar answered Oct 14 '22 19:10

chepner