zoukankan      html  css  js  c++  java
  • 关于几种打开csv文件的探讨

    .csv文件的打开方式可以用csv模块,也可以用打开txt的内置模块,个人感觉用open函数更好用一些

    1.用csv模块

     它的问题是不能一下全部输出整个内容,若果向输出整个还得用append获得 
    import csv
    data = csv.reader(open('hello.csv','r'))
    for line in data:
        print(line)#以列表的形式按行输出
    print(data)#可见输出是以迭代的形式,本身只返回内存地址
    >>>
    ['hello', 'ming', 'lily'] ['1', '2', '3'] ['4', '5', '6'] ['4', '5', '6'] ['4', '5', '6'] ['7', '8', '9'] ['4', '5', '6'] ['4', '5', '6'] ['4', '5', '6'] <_csv.reader object at 0x00000203BA694868>

    2.open直接打开

    方法1:直接加载,按行读取,不是列表的形式

    for line in open('hello.csv','r'):
        print(line.strip())
    >>>
    hello,ming,lily
    1,2,3
    4,5,6
    4,5,6
    4,5,6
    7,8,9
    4,5,6
    4,5,6
    4,5,6

    方法2,read()

    with open('hello.csv','r') as f:
        print(f.read())#输出的是全部内容
        f.seek(0)
        for i in f.read():#但要是用for循环的话,它默认按字母一个一个读取
            print(i,end = '*')
    >>>
    hello,ming,lily
    1,2,3
    4,5,6
    4,5,6
    4,5,6
    7,8,9
    4,5,6
    4,5,6
    4,5,6
    
    h*e*l*l*o*,*m*i*n*g*,*l*i*l*y*
    *1*,*2*,*3*
    *4*,*5*,*6*
    *4*,*5*,*6*
    *4*,*5*,*6*
    *7*,*8*,*9*
    *4*,*5*,*6*
    *4*,*5*,*6*
    *4*,*5*,*6*
    *

    with open('hello.csv','r') as f:
    print(f.read())
    f.seek(0)
    for i in f.read().split(' '): #需要用split(‘ ’)指定分割对象)
    print(i,'*')

    >>>

    hello,ming,lily
    1,2,3
    4,5,6
    4,5,6
    4,5,6
    7,8,9
    4,5,6
    4,5,6
    4,5,6
    
    hello,ming,lily *
    1,2,3 *
    4,5,6 *
    4,5,6 *
    4,5,6 *
    7,8,9 *
    4,5,6 *
    4,5,6 *
    4,5,6 *
     *

    3.readline()方法

    with open('hello.csv','r') as f:
        print(f.readline())#调用一次读一行,类似生成器
        print(f.readline())
        for i in range(10):
            print(f.readline().strip(),'*')

    >>>
    hello,ming,lily
    
    1,2,3
    
    4,5,6 *
    4,5,6 *
    4,5,6 *
    7,8,9 *
    4,5,6 *
    4,5,6 *
    4,5,6 *
     *
     *
     *
    
    
    

    4,readlines方法,一次性全部载入

    with open('hello.csv','r') as f:
        print(f.readlines())
        f.seek(0)
        for i in f.readlines():
            print(i.strip(),'*')

    >>>
    ['hello,ming,lily
    ', '1,2,3
    ', '4,5,6
    ', '4,5,6
    ', '4,5,6
    ', '7,8,9
    ', '4,5,6
    ', '4,5,6
    ', '4,5,6
    ']
    hello,ming,lily *
    1,2,3 *
    4,5,6 *
    4,5,6 *
    4,5,6 *
    7,8,9 *
    4,5,6 *
    4,5,6 *
    4,5,6 *
  • 相关阅读:
    Cypress系列(89)- Cypress.log 命令详解
    Cypress系列(88)- Cypress.spec 命令详解
    Cypress系列(87)- Cypress.browser 命令详解
    Cypress系列(86)- Cypress.version 命令详解
    【原】elastalert 配置使用
    【原】kubeadm 安装高可用集群初始化文件模板
    PageRank 算法-Google 如何给网页排名
    K 均值算法-如何让数据自动分组
    KNN 算法-实战篇-如何识别手写数字
    KNN 算法-理论篇-如何给电影进行分类
  • 原文地址:https://www.cnblogs.com/Zhu-Xueming/p/8379507.html
Copyright © 2011-2022 走看看