python文件读写

readlines

# -*-coding:utf-8-*-
# !/usr/bin/env python
import ast

fout = open('/home/upsmart/1log/warcraft/mid/report01out.csv', 'w')
with open ('/home/upsmart/1log/warcraft/mid/report01.csv','r') as f:
    all = f.readlines()
    # print(type(str))
    for str in all:
        o = []
        list = ast.literal_eval(str)
        # list = eval(str)

        for at in list:
            if(type(at).__name__=='dict'):
                mid =at['mid']
                o.append(mid)
            if(type(at).__name__=='unicode'):
                o.append(at)
        print >> fout ,(",".join(o).encode("utf-8"))
        print(",".join(o).encode("utf-8"))

readlines:读取文件中所有的行放入一个list中,适用于小的文件,如果是大文件内存不够用

readline

# -*-coding:utf-8-*-
# !/usr/bin/env python
import ast

fout = open('/home/upsmart/1log/warcraft/mid/report01out.csv', 'w')
with open ('/home/upsmart/1log/warcraft/mid/report01.csv','r') as f:

    one = f.readline()
    while one:
        print type(one)
        list = ast.literal_eval(one)
        print type(list)
        for at in list :
            o =[]
            if(type(at).__name__ == 'dict'):
                mid = at['mid']
                o.append(mid)
            if(type(at).__name__=='unicode'):
                o.append(at)
        print >> fout ,(",".join(o).encode("utf-8"))
        one = f.readline()

read

# -*-coding:utf-8-*-
# !/usr/bin/env python
f = open('/home/upsmart/1log/warcraft/mid/a.txt')
lines = f.read()
print lines
print(type(lines))
f.close()

注意点:
1) with open as 和open的区别
with open as 读到文件最后会自动关闭文件,即便出现异常。
open直接打开文件,如果出现异常,如读取过程中文件不存在或异常,则直接出现错误,close方法无法执行,文件无法关闭
用with open as比较好

2)ast.literal_eval 和 eval

类型转换
字符串型的list,tuple,dict转变成原有的类型

eval在做计算前并不知道需要转化的内容是不是合法的(安全的)python数据类型。只是在调用函数的时候去计算。如果被计算的内容不是合法的python类型就会抛出异常。

ast.literal则会判断需要计算的内容计算后是不是合法的python类型,如果是则进行运算,否则就不进行运算。

一般采用ast.literal_eval

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值