关于几种打开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('\n'): #需要用split(‘\n’)指定分割对象)
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\n', '1,2,3\n', '4,5,6\n', '4,5,6\n', '4,5,6\n', '7,8,9\n', '4,5,6\n', '4,5,6\n', '4,5,6\n']
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 *

 

posted @ 2018-01-29 21:14  pyming  阅读(1143)  评论(0编辑  收藏  举报