ASH
ASH

Reputation: 20322

Trying to merge all text files in a folder and append file as well

I am trying to merge all text files in a folder. I have this part working, but when I try to append the file name before the contents of each text file, I'm getting a error that reads: TypeError: a bytes-like object is required, not 'str'

The code below must be pretty close, but something is definitely off. Any thoughts what could be wrong?

import glob

folder = 'C:\\my_path\\'

read_files = glob.glob(folder + "*.txt")

with open(folder + "final_result.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(f)
            outfile.write(infile.read())
            outfile.close

Upvotes: 0

Views: 90

Answers (1)

busybear
busybear

Reputation: 10590

outfile.write(f) seems to be your problem because you opened the file with in binary mode with 'wb'. You can convert to bytes using encode You'll likely not want to close outfile in your last line either (although you aren't calling the function anyway). So something like this might work for you:

import glob

folder = 'C:\\my_path\\'

read_files = glob.glob(folder + "*.txt")

with open(folder + "final_result.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(f.encode('utf-8'))
            outfile.write(infile.read())

Upvotes: 2

Related Questions