如何使用Python读取和写入CSV文件? [英] How do I read and write CSV files with Python?

查看:449
本文介绍了如何使用Python读取和写入CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 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

如何读取 example.csv with Python?

How do I read this example.csv with Python?

同样,如果我有

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文件?

How do I write data to a CSV file with Python?

推荐答案

这里有一些最简单的例子,说明如何读取CSV文件以及如何使用Python编写CSV文件。

Here are some minimal complete examples how to read CSV files and how to write CSV files with Python.

纯Python

# -*- coding: utf-8 -*-
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', 'w') as fp:
    writer = csv.writer(fp, delimiter=',')
    writer.writerows(data)

# Read CSV file
with open('test.csv', 'r') 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']]



Pandas



Pandas

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 了解更多信息。请注意,大熊猫会自动推断是否有标题行,但您也可以手动设置。

See read_csv docs for more information. Please note that pandas automatically infers if there is a header line, but you can set it manually, too.

如果您没有听说过 Seaborn ,我建议你看看它。

If you haven't heard of Seaborn, I recommend having a look at it.

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文件读取到元组/它只是工作与这种数据。

After reading the CSV file to a list of tuples / dicts or a Pandas dataframe, it is simply working with this kind of data. Nothing CSV specific.

  • JSON: Nice for writing human-readable data; VERY commonly used (read & write)
  • CSV: Super simple format (read & write)
  • YAML: Nice to read, similar to JSON (read & write)
  • pickle: A Python serialization format (read & write)
  • MessagePack (Python package): More compact representation (read)
  • HDF5 (Python package): Nice for matrices (read & write)
  • XML: exists too *sigh* (read & write)

对于您的应用,以下内容可能很重要:

For your application, the following might be important:


  • 支持其他编程语言

  • /写入效果

  • 压缩(文件大小)

另请参阅:数据序列化格式的比较

如果您是寻找制作配置文件的方法,您可能需要阅读我的简短文章配置文件在Python

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

这篇关于如何使用Python读取和写入CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆