Python 读取.CSV数据

环境:Python3、PyCharm

csv是Comma-Separated Values的缩写,是用文本文件形式储存的表格数据

Python官网中关于CSV的介绍链接

每次行列读取数据前都要进行一次数据读取,否则会出错。


输出全部:

import csv
csv_file = csv.reader(open('/Users/haiqing.dong/Desktop/LOG00001_0012.CSV')) #路径+文件名
print (csv_file)

for i in csv_file:
    print(i)
输出指定行:
import csv
import pandas
csv_file = csv.reader(open('/Users/haiqing.dong/Desktop/LOG00001_0012.CSV'))

for line,i in enumerate(csv_file):

    if line == 234:    #输出指定行
         contents=i
print(contents)

输出指定列:

import csv
import pandas
csv_file = csv.reader(open('/Users/haiqing.dong/Desktop/LOG00001_0012.CSV'))

column = [row[2] for row in csv_file]
print(column)         #输出指定列

上述代码放到一起执行:

import csv
import pandas
csv_file = csv.reader(open('/Users/haiqing.dong/Desktop/LOG00001_0012.CSV'))
#print (csv_file)
#Hlength=len(csv_file.readlines())

for i in csv_file:
      print(i)          #输出所有


csv_file = csv.reader(open('/Users/haiqing.dong/Desktop/LOG00001_0012.CSV'))
for line,i in enumerate(csv_file):

    if line == 234:    #输出指定行
         contents=i
print(contents)

csv_file = csv.reader(open('/Users/haiqing.dong/Desktop/LOG00001_0012.CSV'))
column = [row[2] for row in csv_file]
print(column)         #输出指定列

猜你喜欢

转载自blog.csdn.net/dhq15800562693/article/details/79897094