如何使用python写入.csv文件

时间:2017-09-13 20:27:14

标签: python python-3.x csv

我正在用Python3.6编写一个简单的脚本,并使用csv模块创建一个csv文件。我的代码附在下面,是我在网上找到的多个示例的副本,但是当我运行代码时,我收到错误消息TypeError: a bytes-like object is required, not a 'str'

import csv
File_Name = Test.csv
with open(File_Name, 'wb') as csvfile:
   filewriter = csv.writer(csvfile,delimiter=',')
   filewriter = writerow(['Paul','Mary'])

4 个答案:

答案 0 :(得分:3)

csvwriter实例不应重新分配给。它应该用于写行。

在python 3中,您应该以只写模式打开文件,newline=''documentation

import csv

filename = 'Test.csv'

with open(filename, 'w', newline='') as csvfile:
   file_writer = csv.writer(csvfile,delimiter=',')
   file_writer.writerow(['Paul','Mary'])

答案 1 :(得分:2)

如果您不需要二进制模式,可以使用:

add_action('publish_post', 'undelete_thread');
function undelete_thread($post_id, $post) {
    global $wpdb;
    if ($post->post_type = 'fep_message'){
        $participants = fep_get_participants( $post->post_parent );
        foreach( $participants as $participant ) 
        {
            $query ="SELECT meta_id FROM wp_postmeta WHERE post_id = %s and `meta_key` = '_fep_delete_by_%s'";
            $queryp = $wpdb->prepare($query, array($post->post_parent, $participant));
            if (!empty($queryp)) {
                delete_post_meta($queryp,'_fep_delete_by_' . $participant); 
            }
        }
    }
}

检查表here以查看有关可用的不同模式的详细信息。

答案 2 :(得分:2)

你必须改变' wb'到了' w'和文件名应该在引号中(" Test.csv"或者' Test.csv')见下文

import csv
File_Name = "Test.csv"
with open(File_Name, 'w') as csvfile:
    filewriter = csv.writer(csvfile,delimiter=',')
    filewriter.writerow(['Paul','Mary'])

答案 3 :(得分:1)

问题是你是以二进制模式打开文件

with open(File_Name, 'wb') as csvfile:

这意味着从文件读取的所有数据都以字节对象的形式返回,而不是str。 如果您不需要,请尝试:

with open(File_Name, 'w') as csvfile:

另外,您应该使用writerow的{​​{1}}方法,而不是重新分配它:

csvwriter