如何使用Python读写CSV文件


如何使用Python读写CSV文件


1. 纯Python

# -*- coding: utf-8 -*-

import csv
import sys

# 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
kwargs = {'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 file
kwargs = {'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)

输出

[['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']]

2. Unicode和Python 2.X

如果要编写Unicode,则必须安装unicodecsv。千万不能用打开文件codecs.open,而只是用open。用它写

import unicodecsv as csv
# Write CSV file
with open('test.csv', 'w', newline='') as fp:
    writer = csv.writer(fp, encoding='utf-8')
    # writer.writerow(["your", "header", "foo"])  # write header
    writer.writerows(data)

3. MPU模块

看看我的实用程序包mpu,它是一个超级简单易记的实用程序包:

import mpu.io
data = mpu.io.read('example.csv', delimiter=',', quotechar='"', skiprows=None)
mpu.io.write('example.csv', data)

4. 使用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()