python 读写csv文件

1.忽略第一行标题的基础上
Python2.7

# coding:utf-8

import csv

csv_reader = csv.reader(open(r'C:\Users\thinkPad\Desktop\tweets.csv'))
for row in csv_reader:
    # 条件语句忽略第一行文件数据
    if csv_reader.line_num == 1:
        continue
    print row
    print type(row)
    break

python3

with open(r'D:\PythonFiles\2018second\csv\csvFile1.csv', "r") as csvfile:
   reader = csv.reader(csvfile)
   # 这里不需要readlines
   for line in reader:
       print(line, type(line)) # ['1', '2', '3', 'w'] 

2.写入csv文件

print('开始写入')
csvFile2 = open(r'csvFile1.csv', 'w', newline='')  # 设置newline,否则两行之间会空一行
writer = csv.writer(csvFile2)
data = [[1, 2, 3, 'w'], [1, 2, 3, 'e'], [1, 2, 3, 'r'], [1, 2, 3, 't']]
m = len(data)
for i in range(m):
    writer.writerow(data[i])
csvFile2.close()

如果data[i]只有一个元素会报错的。

with open(r'D:\PythonFiles\2018second\csv\test.csv',"w",newline='') as csvfile:
    writer = csv.writer(csvfile)

    #先写入columns_name
    writer.writerow(["index","a_name","b_name"])
    #写入多行用writerows
    writer.writerows([[0,1,3],[1,2,3],[2,3,4]])

这个如果写入文件已创建啦,再次报错哈。

你可能感兴趣的:(Python高效数据分析)