繁星淼淼
下面是一些最基本的完整示例,如何读取CSV文件以及如何使用Python编写CSV文件。Python 2+3:读取CSV文件纯Python# -*- coding: utf-8 -*-import csvimport sys# Define datadata = [(1, "A towel,", 1.0),
(42, " it says, ", 2.0),
(1337, "is about the most ", -1),
(0, "massively useful thing ", 123),
(-2, "an interstellar hitchhiker can have.", 3)]# Write CSV filekwargs = {'newline': ''}mode = 'w'if sys.version_info < (3, 0):
kwargs.pop('newline', None)
mode = 'wb'with open('test.csv', mode, **kwargs) as fp:
writer = csv.writer(fp, delimiter=',')
# writer.writerow(["your", "header", "foo"]) # write header
writer.writerows(data)# Read CSV filekwargs = {'newline': ''}mode = 'r'if sys.version_info < (3, 0):
kwargs.pop('newline', None)
mode = 'rb'with open('test.csv', mode, **kwargs) as fp:
reader = csv.reader(fp, delimiter=',', quotechar='"')
# next(reader, None) # skip the headers
data_read = [row for row in reader]print(data_read)之后,data_read是[['1', 'A towel,', '1.0'],
['42', ' it says, ', '2.0'],
['1337', 'is about the most ', '-1'],
['0', 'massively useful thing ', '123'],
['-2', 'an interstellar hitchhiker can have.', '3']]Unicode和Python2.x如果要编写unicode,则必须安装unicodecsv..做不用codecs.open但很简单open..用import unicodecsv as csv# Write CSV filewith open('test.csv', 'w', newline='') as fp:
writer = csv.writer(fp, encoding='utf-8')
# writer.writerow(["your", "header", "foo"]) # write header
writer.writerows(data)相关如何以字符串(而不是文件)的形式将数据写入CSV格式?如何在CSV模块中使用io.StringIO()?:这是有趣的,如果你想在不实际存储在服务器上的CSV在飞与瓶。MPU看看我的实用程序包mpu对于一个超级简单和容易记住的人来说:import mpu.io
data = mpu.io.read('example.csv', delimiter=',', quotechar='"', skiprows=None)mpu.io.write('example.csv', data)熊猫import pandas as pd# Read the CSV into a pandas data frame (df)# With a df you can do many things# most important: visualize data
with Seaborndf = pd.read_csv('myfile.csv', sep=',')print(df)# Or export it in many ways, e.g. a list of tuplestuples = [tuple(x) for x i
n df.values]# or export it as a list of dictsdicts = df.to_dict().values()看见read_csv博士想了解更多信息。请注意,熊猫自动推断是否有标题行,但你也可以手动设置它。如果你没听说过海航,我建议你看一看。其他其他一些库支持读取CSV文件,例如:dask.dataframe.read_csvspark.read.csv创建CSV文件1,"A towel,",1.042," it says, ",2.01337,is about the most ,-10,massively useful thing ,123-2,an interstellar hitchhiker can have.,3公共文件结尾.csv处理数据在将CSV文件读取到元组/数据集列表或Pandas dataframe之后,它只是在处理此类数据。没有特定的CSV。备选方案JSON:很适合编写人类可读的数据;非常常用(读写)CSV:超级简单格式(读写)YAML:读起来不错,类似于JSON(读写)泡菜:Python序列化格式(读写)MessagePack (Python包):更紧凑的表示(读写)HDF 5 (Python包):很适合矩阵(读写)XML:也存在*叹息*(朗读,阅读 & 写)对于您的应用程序,以下几点可能很重要:其他编程语言的支持读写性能紧凑(文件大小)另见:数据序列化格式的比较如果您正在寻找一种创建配置文件的方法,您可能需要阅读我的短文。Python中的配置文件