全站搜索未启用
跳到主要内容

6.4.1读文件

此处展示最简单的使用with…as…语句,逐行读取一个file_csv.csv文件的一般过程。

import csv

with open("file_csv.csv","r") as csvfile:

    reader=csv.reader(csvfile)

    for line in reader:

        print(line)

6.4.2写文件

(1)使用writer写入。

(2)使用DictWriter方法写入。

6.4.3使用Pandas对CSV文件进行操作

DataFrame是Python中Pandas库中的一种数据结构,类似于Excel,是一种二维表。DataFrame具有标记轴(行和列)的二维大小可变,可能异构的表格数据结构。算术运算在行标签和列标签上对齐,DataFrame可以被认为是Series对象的类似dict的容器。DataFrame是主要的Pandas数据结构。

6.4.4使用Pandas以及DataFrame对CSV文件进行文件操作

Python中有一个读写CSV文件的包,在使用中,我们可以直接import csv,即调用包即可:

import csv

1.读文件

csv_file = csv.reader(open('file_csv.csv','r'))

next(csv_file, None)    #skip the headers

for user in csv_file:

    print(user)

2.写文件

Import csv

dic = {'aa':25bbxia':26}

csv_file = open('file_csv1.csv', 'w', newline='')

writer = csv.writer(csv_file)

for key in dic:

    writer.writerow([key, dic[key]])

csv_file.close()   #close CSV file

csv_file1 = csv.reader(open('file_csv1.csv','r'))

for user in csv_file1:

print(user)

最后修改: 2020年02月4日 Tuesday 16:12