2

I have many CSV files, and I want to them join then into one txt file, binary format..
The following code give the above error:

import os
from csv import reader
from csv import writer

CONST_DATA_DIR = "F:/Data/"
CONST_DATABIN_DIR = "F:/DataBinary/"


def createFilesArr():
    filesArr = []
    os.chdir(CONST_DATA_DIR)
    for file in os.listdir("."):
        if file.endswith(".csv"):
            filesArr.append(file)
    return filesArr


filesArr = createFilesArr()

newFileName = "oneBinaryFile.txt"
newFile = open(CONST_DATABIN_DIR + newFileName, 'wb')

for file in filesArr:
    currentFile = open(CONST_DATA_DIR + file, 'r', newline='', encoding='UTF8')
    newFile.write(currentFile.read())
    currentFile.close()

newFile.close() 

EDIT:
The CSV files are originally written as a txt type. In the other hand the merge file should be in the binary format.
The process of creating the CSV file is complicated, hence, if possible, I prefer to somehow convert the files before reading.
Any suggestions?

1 Answer 1

7

Python distinguishes between binary and text I/O.

newFile = open(CONST_DATABIN_DIR + newFileName, 'wb')

Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding.

currentFile = open(CONST_DATA_DIR + file, 'r', newline='', encoding='UTF8')
newFile.write(currentFile.read())

In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

All streams are careful about the type of data you give to them. For example giving a str object to the write() method of a binary stream will raise a TypeError. So will giving a bytes object to the write() method of a text stream.

Sign up to request clarification or add additional context in comments.

1 Comment

The question was been editted. Thanks for the current answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.