我有一个内容为example.csv
的文件
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
如何使用Python阅读此example.csv
?
同样,如果我有
data = [(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)]
如何使用Python将data
写入CSV文件?
参考方案
以下是一些最小的完整示例,这些示例如何读取CSV文件以及如何使用Python编写CSV文件。
Python 3:读取CSV文件
纯Python
import csv
# Define data
data = [
(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 file
with open("test.csv", "wt") as fp:
writer = csv.writer(fp, delimiter=",")
# writer.writerow(["your", "header", "foo"]) # write header
writer.writerows(data)
# Read CSV file
with open("test.csv") 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']]
请注意,CSV仅读取字符串。您需要手动转换为列类型。
之前是python 2 + 3版本(link),但是是Python 2 support is dropped。删除Python 2的东西大大简化了这个答案。
有关
处理器
看看我的实用程序包 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 Seaborn
df = pd.read_csv('myfile.csv', sep=',')
print(df)
# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]
# or export it as a list of dicts
dicts = df.to_dict().values()
有关更多信息,请参见 read_csv
docs。请注意,如果有标题行,pandas会自动进行推断,但是您也可以手动设置它。
如果您还没有听说过Seaborn,建议您看看。
其他
许多其他库都支持读取CSV文件,例如:
dask.dataframe.read_csv
spark.read.csv
创建的CSV文件
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
通用文件结尾.csv
处理数据
将CSV文件读取到元组/字典或Pandas数据框列表后,它就可以处理此类数据。没有CSV专用内容。
备择方案
对于您的应用程序,以下内容可能很重要:
另请参阅:Comparison of data serialization formats
如果您想寻找一种制作配置文件的方法,则可能需要阅读我的短文Configuration files in Python
无法注释掉涉及多行字符串的代码 - python基本上,我很好奇这为什么会引发语法错误,以及如何用Python的方式来“注释掉”我未使用的代码部分,例如在调试会话期间。''' def foo(): '''does nothing''' ''' 参考方案 您可以使用三重双引号注释掉三重单引…
Python:BeautifulSoup-根据名称属性获取属性值 - python我想根据属性名称打印属性值,例如<META NAME="City" content="Austin"> 我想做这样的事情soup = BeautifulSoup(f) //f is some HTML containing the above meta tag for meta_tag in soup(…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
您如何在列表内部调用一个字符串位置? - python我一直在做迷宫游戏。我首先决定制作一个迷你教程。游戏开发才刚刚开始,现在我正在尝试使其向上发展。我正在尝试更改PlayerAre变量,但是它不起作用。我试过放在列表内和列表外。maze = ["o","*","*","*","*","*",…
Python uuid4,如何限制唯一字符的长度 - python在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…