Python处理CSV文件

python CSV官方手册:https://docs.python.org/2/library/csv.html

没有所谓的CSV标准,所以格式是由读写它的许多应用程序在操作上定义的。 
缺乏标准意味着不同应用程序生成和使用的数据中经常存在细微差异。这些差异可能会令人讨厌从多个来源处理CSV文件。 
分隔符delimiters和引用字符quoting有所不同,但整体格式足够相似。
总:CSV可以灵活的制定,且能以文本文件形式打开

CSV格式的文档可以方便用Excel打开查看,此外,也可以打开Excel文档,写入CSV格式文档。

Tips:在windows系统下,最好用写字板或者记事本打开csv文件,这样就能看到正确的分割符号。

#-*-coding:utf-8-*-
import csv

# Windows下的分隔符默认的是逗号,而MAC的分隔符是分号。
# 拿到一份用空格分割的CSV文件,在Win下是无法正确读取的,因为CSV模块默认调用的是Excel的规则。

# 参数说明
# 1. delimiter:分割符,规定读取或写入csv文件按照该分隔符进行切片,类似于list.split('.')中的参数
# 2. quotechar:引用符,若csv文件中某个字符串出现了分隔符,则为了区分,需要在该字符串两端加上引用符,比如%,""等。

# 写方式一
# write csv file, with delimiter=' '
# 代码中的newline参数很重要,在写入时,如果没有指定newline='',则会出现空行,因为写入时在'\r\n'前加入了'\r'。
# csv换行操作参考:https://www.jianshu.com/p/0b0337df165a
# 不同操作系统的换行符:
# linux:\n    windows:\r\n    mac:\r
# 或 with open('first_test.csv', 'wb') as csvfile: 方式打开就不会换行
import csv
# with open('first_test.csv', mode='wb', newline='') as csvfile:  # 在Python 2.7.13下,open函数调用newline=''参数会报错
with open('first_test.csv', mode='wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=' ')
    text = []
    with open('./first_test.txt', 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip()
            text.append(line.split(' '))
    for i in text:
        writer.writerow(i)
# 读方式一
with open('first_test.csv', mode='r') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    for i in reader
        print i



# 写方式二
# 使用DictWriter类
# write csv file, with delimiter=' '
import csv
with open('first_test.csv', 'wb') as csvfile:
    fieldnames = ['imgname', 'imgclass']
    writer = csv.DictWriter(csvfile, delimiter=' ', fieldnames=fieldnames) # 写入列的时候,以' '空格作为分割符号(在windows下用)
    # writer.writeheader() # 写入头信息
    with open('./first_test.txt', 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip()
            name, classId = line.split(' ')
            writer.writerow({'imgname': name, 'imgclass': classId})

# 读方式二
# 使用DictReader类

猜你喜欢

转载自blog.csdn.net/tsq292978891/article/details/80176094