Ankit Kumar
Ankit Kumar

Reputation: 117

Issue in writing result into csv file using python 2.7

I am using python 2.7 in my Windows 10(64-bit) system. I have a string str, when executed it shows result as :-

'abcd'
'wxyz'

Now, I want to write this result into result.csv file. So I wrote this following python scrip:-

import csv
with open('result.csv', 'w') as csv_file:
     csv_write = csv.writer(csv_file)
     csv_write.writerow([str]) 

But whenever I execute this script, I am finding only wxyz in result.csv file.

Help me with this issue. Thanks in advance.

Upvotes: 0

Views: 833

Answers (1)

pstatix
pstatix

Reputation: 3848

Python 2.7 csv likes the 'b' mode for writing (in Python 3 just 'w').

Example: Pre-built list of string to file

import csv

strings = []
s1 = 'abcd'
s2 = 'wxyz'
strings.append(s1)
strings.append(s2)

csvf = r"C:\path\to\my\file.csv"

with open(csvf, 'wb') as f:
    w = csv.writer(f, delimiter=',')
    for s in strings:
        w.writerow(s)

Example: Use of reader() to build list of rows to supply writer()

import csv

# read current rows in csv and return reader object
def read(_f):
    with open(_f, 'rb') as f:
        reader = csv.reader(f, delimiter=',')
    return reader

# writes the reader object content
# then writes the new content to end
def write(_f, _reader, _adding):
    with open(_f, 'wb') as f:
        writer = csv.writer(f, delimiter=',')
        for row in _reader:
            writer.writerow(row)
        for row in _adding:
            writer.writerow(row)


strings = []
s1 = 'abcd'
s2 = 'wxyz'
strings.append(s1)
strings.append(s2)

csvf = r"C:\path\to\my\file.csv"

content = read(csvf)

write(csvf, content, strings)

Example: Quick append

import csv

strings = []
s1 = 'abcd'
s2 = 'wxyz'
strings.append(s1)
strings.append(s2)

csvf = r"C:\path\to\my\file.csv"

with open(csvf, 'ab') as f:
    writer = csv.writer(f, delimiter=',')
    for s in strings:
        writer.writerow(s)

References:

In Python 2.x, the reader() and writer() objects required a 'b' flag upon opening. This was a result of how the module handle line termination.

In Python 3.x this was changed so that reader() and writer() objects should be opened with newline=''; line termination is still handled however.

There is also this post and that post covering some of this.

Upvotes: 1

Related Questions