Home > Software design >  How to create a csv file virtually without any physical file / path defined?
How to create a csv file virtually without any physical file / path defined?

Time:03-25

Need to create a csv file and convert it into byte like data for sending as EDI doc. I am trying to achieve this without having a physical file because location/path is unknown. Let me know if there is anyway we could achieve.

with open(
    "/home/some path/*.dat", "r ", newline="\n"
) as write_f:
    data_file = csv.writer(write_f, delimiter=';')
    header_vals = ["header values"]

    query = """data fetching query"""

    data_file.writerow(header_vals)
    self.env.cr.execute(query)
    data_vals = self.env.cr.fetchall()
    data_file.writerows(data_vals)
    po_data = write_f.read(1024)

return po_data

Try 1: Instead of path, tried IO objects(BytesIO/StringIO)

data_file = BytesIO()
data_write = csv.writer(data_file, delimiter=';')

header_vals = ["header values"]

query = """data fetching query"""

data_write.writerow(header_vals)
self.env.cr.execute(query)
data_vals = self.env.cr.fetchall()
data_write.writerows(data_vals)

Received the error at writerow: TypeError: a bytes-like object is required, not 'str'

CodePudding user response:

BytesIO behaves like a file in binary (!) mode. You need to write bytes to it.

But a csv.writer cannot write bytes, it only writes strings. That's the error message you see.

from io import StringIO

buffer = StringIO()
writer = csv.writer(buffer, delimiter=';')

header_vals = ['column_1', 'column_2']
writer.writerow(header_vals)

print(buffer.getvalue())

# => 'column_1;column_2\r\n'
  • Related