-1

I'm trying to write a function that takes three arguments: file1, file2 and new_file, and writes the content of file1 and file2 into new_file.

For example, if I had the files, txt1, txt2:

txt1 contained "Hello world!"

txt2 contained "Can you hear me?"

... and called the function

combine_files(file1, file2, new_file)

new_file should contain "Hello word! Can you hear me?"

My function should not return anything.

My current code looks like this, and I am confident it is far from any way of doing this:

def combine_files(file1, file2, new_filename):
    file1 = "part1.txt"
    file2 = "part2.txt"
    new_filename = "result.txt"

    text1 = open(file1).read()
    text2 = open(file2).read()
    text3 = open(new_filenane, "a")
    text3.write(text1 + text2)

1 Answers1

1

Here's a simple approach using context managers:

def combine_files(file1, file2, new_filename):
    with open(new_filename, 'w') as new_file:
        for file in [file1, file2]:
            with open(file, 'r') as original_file:
                new_file.write(original_file.read())

Context managers save you from having to keep track of open files, and remembering to close them yourself.

A simple context manager tutorial.

tenni
  • 475
  • 3
  • 11