Home > Software engineering >  TypeError: can only concatenate str (not "bytes") to str in Python
TypeError: can only concatenate str (not "bytes") to str in Python

Time:09-28

I wrote the below code to copy the contents of all ".txt" files into a single ".txt" file, it also slightly modifies each line copied. I'm getting the error TypeError: can only concatenate str (not "bytes") to str. Anyone know how to fix this?

import glob
read_files = []
file_name = 'img/img'
for i in range(1,14912):
    read_files.append(file_name str(i) ".txt")

with open("result.txt","wb") as outfile:
    for i,f in enumerate(read_files):
        with open(f, "rb") as infile:
            Lines = infile.readlines()
            for Line in Lines:
                outfile.write(str(i 1) " " Line)

Edit: This error is caused due to last line

CodePudding user response:

You are opening the files in binary mode. There's no (significant, in my opinion) reason to do that: they are text files, so open them in text mode. That's the default, so all you need to do is drop the b from the mode.

with open("result.txt", "w") as outfile:
    for i,f in enumerate(read_files):
        with open(f, "r") as infile:
            Lines = infile.readlines()
            for Line in Lines:
                outfile.write(str(i 1) " " Line)

This does incur some overhead: you have to decode each line when reading, then encode it again when writing. If you weren't modifying the line being written, reading and writing the raw bytes might make sense. (It would also make sense if you planned on using a different encoding for the output file, e.g. switching from ISO-8859 to UTF-8.) If you want to handle the raw bytes, simply encode str(i 1) manually before writing, and use b" " instead of " " to join the two values.

with open("result.txt","wb") as outfile:
    for i,f in enumerate(read_files):
        with open(f, "rb") as infile:
            Lines = infile.readlines()
            for Line in Lines:
                outfile.write(str(i 1).encode()   b" "   Line)
  • Related