使用python 2.7

时间:2017-06-24 13:18:37

标签: python python-2.7 export-to-csv

我在Windows 10(64位)系统中使用python 2.7。我有一个字符串 str ,执行时显示结果为: -

'abcd'
'wxyz'

现在,我想将此结果写入result.csv文件。所以我在python脚本之后编写了这个: -

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

但每当我执行此脚本时,我在result.csv文件中只找到 wxyz

帮我解决这个问题。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

Python 2.7 csv喜欢'b'编写模式(在Python 3中只是'w')。

示例:预先建立的string到文件列表

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)

示例:使用reader()构建要提供的行列表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)

示例:快速追加

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)

<强>参考文献:

Python 2.x中,reader()writer()对象在打开时需要'b'标记。这是模块处理线路终止的结果。

Python 3.x中,这已更改,因此应使用reader()打开writer()newline=''个对象;然而,仍然处理线路终端。

此帖还有this个帖子和that帖子。