zoukankan      html  css  js  c++  java
  • 12.python csv文件写入和读出

    import csv
    
    headers = ["class", "name", "sex", "height", "year"]
    # rows = [
    #     [1, 'xiaoming', 'male', 168, 23],
    #     [1, 'xiaohong', 'female', 162, 22],
    #     [2, 'xiaozhang', 'female', 163, 21],
    #     [2, 'xiaoli', 'male', 158, 21]
    # ]
    # with open("test.csv", "w", newline="") as f:
    #     f_csv = csv.writer(f)
    #     f_csv.writerow(headers)
    #     f_csv.writerows(rows)
    
    # rows = [
    #     {'class': 1, 'name': 'xiaoming', 'sex': 'male', 'height': 168, 'year': 23},
    #     {'class': 1, 'name': 'xiaohong', 'sex': 'female', 'height': 162, 'year': 22},
    #     {'class': 2, 'name': 'xiaozhang', 'sex': 'female', 'height': 163, 'year': 21},
    #     {'class': 2, 'name': 'xiaoli', 'sex': 'male', 'height': 158, 'year': 21},
    # ]
    # with open("test2.csv", "w", newline="") as f:
    #     f_csv = csv.DictWriter(f, headers)
    #     f_csv.writeheader()
    #     f_csv.writerows(rows)
    
    # 列表读取
    with open("test2.csv") as f:
        f_csv = csv.reader(f)
        for row in f_csv:
            print(row)
    
    # 字典读取
    with open("test2.csv") as f:
        f_csv = csv.DictReader(f)
        for row in f_csv:
            print(row["sex"])
  • 相关阅读:
    Atom 和 markdown 基本使用
    c++11 正则表达式基本使用
    Emacs 之窗口管理
    Emacs 之列编辑模式
    Emacs 之查看帮助
    使用 json_in_java
    Linux服务 httpd
    Linux 编译安装BIND
    Kerberos
    Linux服务 DNS&BIND
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/11262994.html
Copyright © 2011-2022 走看看