1读写模式

r以读方式打开文件,可读取文件信息
w已写方式打开文件,可向文件写入信息。如文件存在,则清空,再写入
a以追加模式打开文件,打开文件可指针移至末尾,文件不存在则创建
r+以读写方式打开文件,可对文件进行读和写操作
w+消除文件内容,以读写方式打开文件
a+以读写方式打开文件,文件指针移至末尾
b以二进制打开文件

2csv

2.1基本用法

#coding=utf-8
import csv
import codecs
import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
#创建写入
csvfile=open('csv_test.csv','wb')
# csvfile.write(codecs.BOM_UTF8)#防止文件中显示中文乱码(并非乱码),若注意生成文件编码,用notepad++转码也能正常显示。
writer=csv.writer(csvfile)
writer.writerow(['姓名','年龄','电话'])
data=[('alex','23','139'),('tom','43','189')]
writer.writerows(data)
csvfile.close() #读取
csvfile=open('csv_test.csv','rb')
reader=csv.reader(csvfile)
for line in reader:
print line
csvfile.close()

2.2DictWriter

我主要想说的是DictWriter,我为什么会喜欢使用DictWriter呢,因为普通的writer你需要手工去构建列表,尤其是通过表单提交的时候,而我之前因为一直在zope平台上开发,而zope支持一种高级表单数据模型,也就是可以通过定义表单的时候加入相应的标志来使提交后的表单数据自动的生成一个记录(records)类型,也就是生成一个每项数据都是一个字典的列表。这样,我就可以非常方便的直接把表单数据传给 DictWriter而生成csv,当然这个是在你能保证数据的正确性的前提下。好下面我来简单的说明一下这种zope的高级表单数据类型。

例子:

<form action='test_form_action' method=post>
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
<input type="submit" value="Submit CSV" />
</form>

表单提交后的结果是:

rows = [{'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'}]

这样就可以直接调用DictWriter.writerows方法来处理了:

import csv

fieldnames = ['Column1', 'Column2', 'Column3', 'Column4']

dict_writer = csv.DictWriter(file('your.csv', 'wb'), fieldnames=fieldnames)

dict_writer. writeheader(fieldnames) # CSV第一行需要自己加入

dict_writer.writerows(rows)  # rows就是表单提交的数据

  

*注意:这里的csv文件写入需要External Method的支持,因为在zope中由于权限沙箱的问题是不能直接操作csv模块来读写文件系统的。

3txt读写

#coding=utf-8
#文件创建和写入
f=open('test.txt','w')
f.write('hello world')#数据只写到缓存,未保存到文件
f.close()#保存到文件 f1=open('test.txt','r+')#r+模式不会清空文件,而是替换内容
f1.write('hello boy')
f1.close() f2=open('test.txt','a')#a模式实现追加
f2.write('\nhello girl')
f2.writelines(['\n你好','\n再见'])#多行写入
f2.flush()#将修改写入文件,无须关闭

demo:

#文件读取(按指针)
f3=open('test.txt')
print f3.read(1)
f3.seek(1,1)
'''f.seek(偏移量,选项)
(1)选项=0,表示将文件指针指向从文件头部到“偏移量”字节处
(2)选项=1,表示将文件指针指向从文件的当前位置,向后移动“偏移量”字节
(3)选项=2,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节
'''
print f3.read(1)
print f3.tell()#获取指针位置
f3.close() #文件读取(按行)
'''
f3.read()#读取所有
f3.readline()#逐行读取
f3.next()#类readline,未读到报错
f3.readlines()#列表形式存放
for i in open('test.txt'):
print i
''' #文件操作(查找) #方法一:全内容查找
f4=open('test.txt')
source=f4.read()
f4.close()
s=len(re.findall('hello',source))
print s #方法二:按行查找
f5=open('test.txt')
count=0
for i in f5.readlines():
li=re.findall('hello',i)
if len(li)>0:
count=count+len(li)
print 'search',count,'hello'
f5.close() #文件操作(替换)实例:把test.txt 中的hello全部换为"hi",并把结果保存到myhello.txt中。
f6=open('test.txt')
f7=open('myhello.txt','a')
for i in f6.readlines():
f7.write(i.replace('hello','hi'))
f6.close()
f7.close() #实例:读取文件test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为result.txt。
f = open('cdays-4-test.txt')
result = list()
for line in f.readlines(): # 逐行读取数据
line = line.strip() #去掉每行头尾空白
if not len(line) or line.startswith('#'): # 判断是否是空行或注释行
continue #是的话,跳过不处理
result.append(line) #保存
result.sort() #排序结果
print result
open('result.txt','w').write('%s' % '\n'.join(result)) #保存入结果文件

  

 

csv、txt读写及模式介绍的更多相关文章

  1. 如何处理大体积 XLSX/CSV/TXT 文件?

    在开发过程中,可能会遇到这样的需求,我们需要从本地的 Excel 或 CSV 等文件中解析出信息,这些信息可能是考勤打卡记录,可能是日历信息,也可能是近期账单流水.但是它们共同的特点是数据多且繁杂,人 ...

  2. CQRS读写职责分离模式(Command and Query Responsibility Segregation (CQRS) Pattern)

    此文翻译自msdn,侵删. 原文地址:https://msdn.microsoft.com/en-us/library/dn568103.aspx 通过使用不同的接口来分离读和写操作,这种模式最大化了 ...

  3. 8086汇编语言学习(二) 8086汇编开发环境搭建和Debug模式介绍

    1. 8086汇编开发环境搭建 在上篇博客中简单的介绍了8086汇编语言.工欲善其事,必先利其器,在8086汇编语言正式开始学习之前,先介绍一下如何搭建8086汇编的开发环境. 汇编语言设计之初是用于 ...

  4. akka-typed(8) - CQRS读写分离模式

    前面介绍了事件源(EventSource)和集群(cluster),现在到了讨论CQRS的时候了.CQRS即读写分离模式,由独立的写方程序和读方程序组成,具体原理在以前的博客里介绍过了.akka-ty ...

  5. C#中的CSV文件读写

    目录 CSV文件标准 文件示例 RFC 4180 简化标准 读写CSV文件 使用CsvHelper 使用自定义方法 基于简化标准的写CSV文件 使用TextFieldParser解析CSV文件 使用正 ...

  6. [Python]-pandas模块-CSV文件读写

    Pandas 即Python Data Analysis Library,是为了解决数据分析而创建的第三方工具,它不仅提供了丰富的数据模型,而且支持多种文件格式处理,包括CSV.HDF5.HTML 等 ...

  7. CDN模式介绍

    body{ font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif; }        CDN(content delivery networ ...

  8. 企业IT管理员IE11升级指南【4】—— IE企业模式介绍

    企业IT管理员IE11升级指南 系列: [1]—— Internet Explorer 11增强保护模式 (EPM) 介绍 [2]—— Internet Explorer 11 对Adobe Flas ...

  9. Spark on YARN两种运行模式介绍

    本文出自:Spark on YARN两种运行模式介绍http://www.aboutyun.com/thread-12294-1-1.html(出处: about云开发)   问题导读 1.Spark ...

随机推荐

  1. [Luogu4475]巧克力王国

    luogu 题意 平面上有\(n\)个点,每个点\((x_i,y_i)\),价值为\(w_i\).\(m\)次询问,每次给出\(a_i,b_i,c_i\)求满足\(a_ix+b_iy<c_i\) ...

  2. bootstrap table 兼容ie8 -- refreshOptions

    今天项目使用 bootstrap table 在ie8下发现 方法 refreshOptions 报错. 经过调试监控发现错误如下: 153 行 代码 Object.getOwnPropertyNam ...

  3. C#反射 -- 基础

    两个现实中的例子:1.B超:大家体检的时候大概都做过B超吧,B超可以透过肚皮探测到你内脏的生理情况.这是如何做到的呢?B超是B型超声波,它可以透过肚皮通过向你体内发射B型超声波,当超声波遇到内脏壁的时 ...

  4. 一周学会HTML----Day03常用标签(下)

    form 标签 表单(重要) 表单用途 用于收集用户信息,提交给服务器 基本使用 (action,method,enctype) 要提交的表单必须放到form里 input select textar ...

  5. Excel 2007 打开 UTF-8 编码 CSV 文件的乱码BUG

    http://blog.sina.com.cn/s/blog_6c3b65fd01018dgq.html 打开UTF-8编码的CSV方法: 1) 打开Excel 2007 2) 执行“数据”-> ...

  6. DHCP(四)

    确认阶段:即DHCP服务器确认分配级DHCP客户端IP地址的阶段.某个DHCP服务器在收到DHCP客户端发来的DHCP Request报文后,只有DHCP客户端选择的服务器会进行如下操作:如果确认将地 ...

  7. iPhone之IOS5内存管理(ARC技术概述)

    ARC(Automatic Reference Counting )技术概述 此文章由Tom翻译,首发于csdn的blog,任何人都可以转发,但是请保留原始链接和翻译者得名字.多谢! Automati ...

  8. ISO模型的七个分层

    要想理解socket首先得熟悉一下TCP/IP协议族, TCP/IP(Transmission Control Protocol/Internet Protocol)即传输控制协议/网间协议,定义了主 ...

  9. c#编写的基于TCP通信的微风IM 版本3 新年新UI

    电商商模 背景:来源,产生运营模式:模式特点,服务对象,业务开展,赢利点,扩 张点,定价策略行业分析:市场分析:DX,企业,政策,经济,文化,技术 网站架构:频道,版块,功能体系 项目推广:地面推广, ...

  10. php文件上传总结

    前言: 学习php中 1.表单代码: <html> <head> <title>文件上传</title> </head> <body ...