0

The following code writes a CSV file in UTF-8 format. The csv file is stored in the filesystem.

with open('sample.csv', 'w', newline='', encoding='utf-8') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    csvfile.write('\ufeff')
    spamwriter.writerow("嗨")

Now I don't want to write to the fileystem anymore, I only want to store the CVS into a StringIO buffer. How should I do this?

3 Answers 3

2

Why don't you just write the lines?

import io

s = io.StringIO()

with open('sample.csv') as file:
    for line in file:
        s.write(line)

s.seek(0)
for line in s:
    print(line)
Sign up to request clarification or add additional context in comments.

Comments

1
    buf = StringIO()
    buf.write('\ufeff')
    writer = csv.writer(
        buf,
        "UNIX",
        delimiter=delimiter,
        quoting=csv.QUOTE_MINIMAL,
    )
    writer.writerow(h for h in header)
    for line in lines:
        writer.writerow(l for l in line)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0
import csv
import os

filename = "temp.csv"
with open(filename, 'w', encoding='utf-8') as fp:
    fp.write('\ufeff')
    csv_writer = csv.writer(fp, quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['嗨', '="00000011"', 'Lovely Spam', 'Wonderful Spam'])

buffer = open(filename, 'r').read()
print (buffer)
os.unlink(filename)


f= open("final.csv", "w")
f.write(buffer)
f.close()

Comments

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.