可以不使用CSV模块

逐行处理:

for line in open("samples/sample.csv"):
title, year, director = line.split(",")
print year, title 使用CSV:
import csv
reader = csv.reader(open("samples/sample.csv"))
for title, year, director in reader:
print year, title 将数据存为csv格式:
import csv
import sys
 
data = [
("And Now For Something Completely Different", 1971, "Ian MacNaughton"),
("Monty Python And The Holy Grail", 1975, "Terry Gilliam, Terry Jones"),
("Monty Python's Life Of Brian", 1979, "Terry Jones"),
("Monty Python Live At The Hollywood Bowl", 1982, "Terry Hughes"),
("Monty Python's The Meaning Of Life", 1983, "Terry Jones")
]
 
writer = csv.writer(sys.stdout)
 
for item in data:
writer.writerow(item) 怎么获取csv reader 对象的len?
参考:http://stackoverflow.com/questions/2890549/number-of-lines-in-csv-dictreader csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

I've gotten used to generating CSV (comma separated value) files in Python for these folks. Ever so often, someone sends me a CSV file they have created via Excel. Invariably, I will get the following error when trying to read that file with Python:

_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

This is annoying, but the solution to the problem is to open the file with universal newline mode enabled. This means using the mode 'U' or 'rU' in your open() function call. For example:

reader = csv.reader(open("data.csv", 'rU'), dialect='excel')

According to the open() documentation, universal newline mode accepts \n,\r, and \r\n as valid newline characters.

python with用法:
with是python2.5以后才有的,它实质是一个控制流语句,with可以用来简化try-finally语句。它的主要用法是实现一个类__enter__()和__exit__()方法,基本形式如下
class controlled_execution:
def _enter__(self):
set things up
return thing
def __exit__(self, type, value, traceback):
tear thing down
with controlled_execution() as thing:
some code

在实际的运行过程中,python会首先运行enter里的代码,返回thing,作为as 后面的变量值,然后再运行with模块中的代码,最后会自动执行exit中的代码,而不管with中的代码运行结果如何。这也就是with能简化try-finally语句的原因。所以with通常用在读取文件的操作中,将文件句柄的关闭操作放在exit方法中,这样就不会因忘记释放文件句柄而产生可能出现的错误。

另外,exit()方法的返回值可以用来指示with部分的代码出现的异常是否需要raise,如果返回false,则会raise,否则,不进行任何操作。

在 try、raise 陳述句 中有個讀取檔案的範例:

file = open('demo.py', 'r', encoding='UTF-8')
try:
for line in file:
print(line, end='')
except:
print('讀取檔案發生錯誤')
finally:
file.close()

為了要處理檔案讀取過程中發生的例外,並且最後確定檔案一定會關閉,你使用了try..except...finally語句,實際上,在Python 3(或2.6)中,你可以使用with as語句來簡化程式的撰寫:

with open('demo.py', 'r', encoding='UTF-8') as file:
for line in file:
print(line, end='')

with之後的運算式傳回的物件,可以使用as指定給變數來參考,在上面的例子中,file所參考到的物件,最後會被自動關閉,即使在with as的區塊中發生了例外,最後一定會關閉file所參考的物件。

實際上,只要物件支援環境管理協定(Context Management Protocol),就可以使用with as語句。支援環境管理協定的物件,必須實作__enter__()與__exit__()兩個方法,這樣的物件稱之為環境管理員(Context Manager)。

with陳述句一開始執行,就會進行__enter__()方法,該方法傳回的物件,可以使用as指定給變數(如果有的話),接著就執行with區塊中的程式碼。

如果with區塊中的程式碼發生了例外,則會執行__exit__()方法,並傳入三個引數,這三個引數,與 再看 try、raise 中所提到的 sys.exc_info() 傳回的三個值是相同的,也就是例外的類型、例 外訊息以及traceback物件。此時__exit__()方法若傳回False,則例外會被重新丟出,否則例外就停止傳播,通常__exit__()會傳回False以在with之外還可以處理例外。

如果with區塊中沒有發生例外而執行完畢,則也是執行__exit__()方法,此時__exit__()的三個參數都接收到None。

所以,假設你要自行實作一個可以自動關閉檔案的物件,則可以如下:

class FileReader:
def __init__(self, filename):
self.filename = filename def __enter__(self):
self.file = open(self.filename, 'r', encoding='UTF-8')
return self.file def __exit__(self, type, msg, traceback):
if type:
print(msg) # 作你的例外處理
self.file.close()
return False

接下來你就可以在FileReader物件上使用with as語句。例如:

with FileReader('demo.py') as file:
    for line in file:
        print(line, end='')
参考:http://www.pythonclub.org/python-files/csv

http://docs.python.org/2/library/csv.html

Python CSV文件处理/读写及With as 用法的更多相关文章

  1. python CSV 文件的读写

    1.CSV文件 import csv with open(r"E:\code\0_DataSet\tianchi_2015_mobile_recommand\fresh_comp_offli ...

  2. python之文件的读写和文件目录以及文件夹的操作实现代码

    这篇文章主要介绍了python之文件的读写和文件目录以及文件夹的操作实现代码,需要的朋友可以参考下 为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成操作之后可以迅速关闭文件,防止一些无用 ...

  3. python 下 excel,csv 文件的读写

    python 可以用利用xlrd 库读取数据excel数据,可以用xlwt写入excel数据,用csv 操作csv文件 xlrd xlwt  python 模块 官方链接  https://pypi. ...

  4. Python 标准库 csv —— csv 文件的读写

    csv 文件,逗号分割文件. 0. 读取 csv 到 list from csv import reader def load_csv(csvfile): dataset = [] with open ...

  5. Python对csv文件的读写操作

    python内置了csv模块,用它可以方便的操作csv文件. 1.写文件 (1)写文件的方法一 import csv # open 打开文件有多种模式,下面是常见的4种 # r:读数据,默认模式 # ...

  6. Python实现对CSV文件的读写功能

    我们要处理csv文件,首先要的导入csv模块 import csv #读取csv文件def readCsv(path): #传入变量csv文件的路径 list=[] #定义一个空列表 with ope ...

  7. Python 【文件的读写】

    文件读写 A 读取文件 读文件三步:开——读——关.file1 = open('/Users/Ted/Desktop/test/abc.txt','r',encoding='utf-8')第一个参数是 ...

  8. csv文件的读写

    # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. "&quo ...

  9. python对文件的读写

    文件 File 什么是文件 文件是用于数据存储和单位 文件通常用来长期存储数据 文件中的数据是以字节为单位进行顺序存储的 文件的操作流程: 1. 打开文件 2. 读/写文件 3. 关闭文件 注: 任何 ...

随机推荐

  1. Hql中占位符(转)

    在新的Hibernate 4版本中,对于Hql有一点点改变,如果你还是按照以前的方式去编写HQL并且用了以下占位符的方式,就会得到一个警告. 参考资料:https://hibernate.atlass ...

  2. 在zendstudio上配置SVN

    本文介绍zendstudio结合SVN的使用方法. 一.部署svn服务器 直接安装用svn软件,配置太过麻烦,用户和版本库.权限管理不太方便.推荐使用CollabNetSubversionEdge.以 ...

  3. HBase shell 操作命令记录

    创建表:create 'tablename','column cluseter:column1,column2...columnn','column cluster:column1,column2.. ...

  4. hadoop搭建杂记:Linux下hadoop的安装配置

    VirtualBox搭建伪分布式模式:hadoop的下载与配置 VirtualBox搭建伪分布式模式:hadoop的下载与配置 由于个人机子略渣,无法部署XWindow环境,直接用的Shell来操作, ...

  5. jQ中prop与attr的区别

    1.prop适用于HTML元素本身就带有的固有属性 2.attr适用于HTML元素我们自定义的属性 <input type="checkbox" value="复选 ...

  6. 安卓自定义view_GDI绘图 _2d绘图_canvas绘图

    2014年到2016年 发生了很多事情,如今已成定局,现在想忘掉这些烦恼的事情,找点以前想干没有干的事情来做,塞满大脑就不去想了. 之前,一直想做一款挂机类游戏,各种平台和开发语言都选择过了,从htm ...

  7. CSS Flex

    关于flex 请看这里  https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 太详细啦!!!  还通俗易懂!!! 没啥好说的 不过上面那篇文 ...

  8. Linux例行工作crontab

    第一步编辑要定时执行的脚本: myScript.sh myScript.sh的内容为:touch /root/`date +%F' '%T`.txt 为myScript.sh增加可执行权限:chmod ...

  9. Q_D宏

    Qt 源码中有很多Q_Q和Q_D宏,使用这些宏的地方总会看到有q指针和d指针,查了查KDE文档,大体搞清了其中的机理,欧也!Qt的这些私有数据访问策略还是挺值得借鉴.下面就简单总结一下. 访问器 , ...

  10. 解决[warn] _default_ VirtualHost overlap on port 80, the first has precedence问题

    问题背景: 在apache的httpd.conf里新增加了1个VirtualHost,域名是xxx.com,此时,服务器总共2个VirtualHost ,service httpd restart的时 ...