zoukankan      html  css  js  c++  java
  • pythonCSV模块

    在爬虫过后会取得很多信息! 将信息存起来方法还很多中!今天提一下CSV模块

    导入模块

    import csv

    这里先写个列表

    rows = [['zhangsan',20],['lisi',22],['wangwu',23],['zhaoliu',18]]
    1,写入信息

    with open('test.csv','w',newline='')as my_csv:
    write = csv.writer(my_csv)
    for row in rows:
    write.writerow(row) #写一行
    2,读取文件

    with open('test.csv','r',newline='')as my_csv:
    reader = csv.reader(my_csv)
    print(type(reader))
    print([row for row in reader])
    def write_data():
    colums = int(input('请输入数据的总列数:'))
    my_list =[]
    while 1:
    my_list.append([input('第{}列:'.format(i +1)) for i in range(0,colums)])
    isGoing = input('是否继续循环(Y/N)?')
    if isGoing !='Y':
    break
    print(my_list)

    with open('test2.csv','w',newline='')as my_csv:
    # 通过CSV模块创建一个用于写入数据的对象
    writer = csv.writer(my_csv)
    for row in my_list:
    writer.writerow(row)
    3,写入表头数据

    list_test = [
    {"name":"python2","version":"2.7"},
    {"name":"python3","version":"2.8"},
    {"name":"python4","version":"2.9"},
    {"name":"python5","version":"3.0"},
    {"name":"python6","version":"3.1"}
    ]
    with open('dict.csv','w',newline='')as my_csv:
    # 创建一个用于写入数据的对象
    keys = [key for key in list_test[0]]
    # print('keys:',keys)
    #fieldnames 用于设置CSV文件的表头内容
    writer = csv.DictWriter(my_csv,fieldnames=keys)
    # 写入表头内容
    writer.writeheader()

    for dict in list_test:
    writer.writerow(dict)
    读取上面代码

    with open("dict.csv",'r')as my_csv:
    reader = csv.DictReader(my_csv)
    print([d for d in reader])
     
    ---------------------
    版权声明:本文为CSDN博主「DonQuixote_」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/donquixote_/article/details/81543979

  • 相关阅读:
    js 为表格增加行 动态
    百度测试新搜索结果页面 改进灵感来自谷歌?
    多线程程序中使用fork的问题
    C++ struct和class的区别
    J2SE 5 HotSpot JVM 解释
    并行优化、xvout
    C++基础:纯虚函数和抽象类
    C++的四种cast
    logcat过滤输出
    C++虚函数和纯虚函数(2)
  • 原文地址:https://www.cnblogs.com/valorchang/p/11320028.html
Copyright © 2011-2022 走看看