美文网首页
CSV文件的读写

CSV文件的读写

作者: 逍遥_yjz | 来源:发表于2018-12-21 15:44 被阅读0次

    1.测试列表写入CSV文件

    文件csvFile1.csv


    # coding:utf-8
    import csv
    
    # 测试列表写入CSV文件
    def list_write_csv():
        print('开始写入')
        csvFile2 = open(r'D:\PythonFiles\2018second\csv\csvFile1.csv', 'w', newline='')  # 设置newline,否则两行之间会空一行
        writer = csv.writer(csvFile2)
        data = [[1, 2, 3, 'w'], [1, 2, 3, 'e'], [1, 2, 3, 'r'], [1, 2, 3, 't']]
        m = len(data)
        for i in range(m):
            print(data[i])
            writer.writerow(data[i])
        csvFile2.close()
    

    输出:

    开始写入
    [1, 2, 3, 'w']
    [1, 2, 3, 'e']
    [1, 2, 3, 'r']
    [1, 2, 3, 't']
    

    2.读取CSV文件

    文件csvFile1.csv

    #读取csv文件
    def read_csv():
        with open(r'D:\PythonFiles\2018second\csv\csvFile1.csv', "r") as csvfile:
            reader = csv.reader(csvfile)
            # 这里不需要readlines
            for line in reader:
                print(line, type(line)) # ['1', '2', '3', 'w'] <class 'list'>
    
    

    输出:

    ['1', '2', '3', 'w'] <class 'list'>
    ['1', '2', '3', 'e'] <class 'list'>
    ['1', '2', '3', 'r'] <class 'list'>
    ['1', '2', '3', 't'] <class 'list'>
    

    3.测试列表写入CSV文件

    def test_with_write():
        with open(r'D:\PythonFiles\2018second\csv\test.csv',"w",newline='') as csvfile:
            writer = csv.writer(csvfile)
    
            #先写入columns_name
            writer.writerow(["index","a_name","b_name"])
            #写入多行用writerows
            writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
    

    输出:
    文件test.csv


    参考资料:
    https://blog.csdn.net/xiaoyaozizai017/article/details/79844633

    相关文章

      网友评论

          本文标题:CSV文件的读写

          本文链接:https://www.haomeiwen.com/subject/atomkqtx.html