0

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.

Ankit Kumar
  • 107
  • 1
  • 3
  • 14

1 Answers1

1

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.

pstatix
  • 3,611
  • 4
  • 18
  • 40
  • Thanks for the information @pstatix. But I want to extract 'abcd' and 'wxyz' from str and and write it to csv file.How should I do it? – Ankit Kumar Jun 24 '17 at 13:45
  • @user3766871 What do you mean by "extract...from str"? If you have a variable called `str` and those values are inside it; that's a whole other question. – pstatix Jun 24 '17 at 13:49