Copy a file line by line in python

前端 未结 4 1563
半阙折子戏
半阙折子戏 2021-01-12 17:48

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.

Howeve

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 18:16

    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,
    

提交回复
热议问题