csv、txt读写及模式介绍

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))        #保存入结果文件

  

 

 

转载于:https://www.cnblogs.com/BigFishFly/p/6337157.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值