如何使用Python读写CSV文件?

时间:2017-01-11 07:31:24

标签: 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

如何使用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文件?

5 个答案:

答案 0 :(得分:33)

以下是一些最简单的完整示例,介绍如何读取CSV文件以及如何使用Python编写CSV文件。

Python 2 + 3:读取CSV文件

Pure 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)

之后,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和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)

相关

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 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文件,例如:

创建的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文件读取到元组/ dicts列表或Pandas数据帧后,它只是处理这种数据。没有特定的CSV。

替代

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

  • 其他编程语言的支持
  • 阅读/写作表现
  • 紧凑性(文件大小)

另请参阅:Comparison of data serialization formats

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

答案 1 :(得分:2)

编写CSV文件

首先你需要导入csv

例如:

import csv

with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

答案 2 :(得分:1)

如果需要 - 在不使用 csv 模块的情况下读取 csv 文件:

rows = []
with open('test.csv') as f:
    for line in f:
        # strip whitespace
        line = line.strip()
        # separate the columns
        line = line.split(',')
        # save the line for use later
        rows.append(line)

答案 3 :(得分:0)

import csv
with open(fileLocation+'example.csv',newline='') as File: #the csv file is stored in a File object

    reader=csv.reader(File)       #csv.reader is used to read a file
    for row in reader:
        print(row)

答案 4 :(得分:0)

要使用熊猫读取csv文件

use pd.read_csv("D:\\sample.csv")

using only python :

fopen=open("D:\\sample.csv","r") 

print(fopen.read())

创建并写入csv文件

下面的示例演示如何创建和写入一个csv文件。要创建一个动态文件编写器,我们需要导入一个包导入csv,然后需要创建一个文件实例,其文件引用为Ex:

with open("D:\sample.csv","w",newline="") as file_writer

如果该文件不存在上述文件目录,则python将在指定目录中创建相同文件,并且w代表写操作,如果要读取文件,请替换w r或附加到现有文件然后a

newline=""指定每次创建行时都会删除一个多余的空行,因此为了消除空行,我们使用newline="",使用类似以下的列表创建一些字段名(列名):

fields=["Names","Age","Class"]

然后适用于以下作家实例:

writer=csv.DictWriter(file_writer,fieldnames=fields)

这里使用字典编写器并分配列名,使用writer.writeheader()将列名写入csv并使用writer.writerow({"Names":"John","Age":20,"Class":"12A"})写入值,而写文件值必须使用字典方法传递,此处键是列名,值是您各自的键值。

导入csv:

with open("D:\sample.csv","w",newline="") as file_writer:

fields=["Names","Age","Class"]

writer=csv.DictWriter(file_writer,fieldnames=fields)

writer.writeheader()

writer.writerow({"Names":"John","Age":21,"Class":"12A"})