def copy_file(source_file, target_file): with open(source_file, "r") as s: read_data = s.read() with open(target_file, "w") as t: t.write(read_data)
Copy Content from One File to Another
Write a function that receives a path to two text files as parameters and copies
the content of the first file into the second, overwriting the content of the second
file if it's not empty.
test copy file - Run Test
import tempfile def test_copy_file(): fp1 = tempfile.NamedTemporaryFile(mode="w") fp1.write('this is line 1\n') fp1.write('this is line 2\n') fp1.write('this is line 3\n') fp1.flush() fp2 = tempfile.NamedTemporaryFile(mode="w") copy_file(fp1.name, fp2.name) fp1.close() with open(fp2.name) as fp2: assert len(fp2.readlines()) == 3 fp2.seek(0) assert fp2.readlines() == 'this is line 3\n'