Search code examples
pythonconcatenation

Combine txt files with file names


I want to combine txt files into a single txt file. The code below works fine. But the only problem is that I don't understand which strings came from which txt.

import glob

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

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

I want to result to look like:

file1.txt
string1
string2
file2.txt
string3
string4

Solution

  • The code below works exactly as I want it to. First, I tried printing the f variable holding the file name. outfile.write(f) But since I opened the file in "rb" mode, I got the error: TypeError: a bytes-like object is required, not 'str'. I changed the code to outfile.write(f.encode()) upon my friend's suggestion. Here, I don't know what the encode() method does. Maybe someone explains. Then, I used outfile.write("\n".encode()) to start a new line after the filename. The final code is:

    import glob
    
    read_files = glob.glob("*.txt")
    
    with open("result.txt", "wb") as outfile:
        for f in read_files:
            with open(f, "rb") as infile:
                outfile.write(f.encode())
                outfile.write("\n".encode())
                outfile.write(infile.read())