I've been taught the best way to read a file in python is to do something like:
with open('file.txt', 'r') as f1:
for line in f1:
do_something()
But I have been thinking. If my goal is to copy the contents of one file completely to another, are there any dangers of doing this:
with open('file2.txt', 'w+') as output, open('file.txt', 'r') as input:
output.write(input.read())
Is it possible for this to behave in some way I don't expect?
Along the same lines, how would I handle the problem if the file is a binary file, rather than a text file. In this case, there would be no newline characters, so readline()
or for line in file
wouldn't work (right?).
EDIT Yes, I know about shutil
. There are many better ways to copy a file if that is exactly what I want to do. I want to know about the potential risks, if any, of this approach specifically, because I may need to do more advanced things than simply copying one file to another (such as copying several files into a single one).