[Tutor] Copying one text file into another
Mats Wichmann
mats at wichmann.us
Tue Aug 3 19:07:59 EDT 2021
On 8/3/21 12:55 PM, Ed Connell wrote:
> Suppose you have two text files, A.txt and B.txt. You want to copy A into
> B at some designated place .Of course there is copy and paste, but I got
> interested in how you could do this with Python. Can you help?
File systems don't provide an insert method for files, so you are going
to have to rewrite the target file. As long as that's okay, there are
various approaches. If the files aren't massive, and you can do it in
memory then it's basically: read file A into an appropriate Python data
structure X, read file B into an appropriate data structure Y, insert X
into Y, write Y out to file B.
("appropriate data structure" - it could be a list of lines if the
operation is to be line-based, bytes, bytearray, etc. depending on
what's in the files)
More information about the Tutor
mailing list