python2.7中字典,文件读写,文件替换记录

1.引入相关模块

import datetime
import sys
import re
import os
import io
 

2. 设置字符集

if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    print sys.getdefaultencoding()
    #print "掉头".encode('utf-8')
    #print('i am request,\xE6\x88\x91\xE6\x98\xAF\xE8\xAF\xB7\xE6\xB1\x82'.decode('utf-8').encode('utf-8'))
    

3.编写main函数

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print "please input deal file"
        sys.exit()
    main()

4.map遍历

def testmap(map):
    for key in map.keys():
            #print key, map[key]
            #print(key, map[key]) 
            print key 

5.文件读写

def testreadfile(file):
    #f = io.open(file, 'r', encoding="utf-8")
    with io.open(file, "r", encoding="utf-8") as f:
        #for line in f:
        #    print line
        #f.close() 
        print f.read()
        f.close()  

def testwritefile(file):
    with io.open(file, "w+", encoding="utf-8") as fp:
        fp.writelines(u"1234" + u"\n")
        fp.writelines(u"中国很棒" + u"\n")
        fp.writelines(u"1234" + u"\n")
        fp.writelines(u"中国加油" + u"\n")
    fp.close()

6.文件内容替换

def filereplace1(filename):
    file_data = ""
    old_str = """
    new_str = ""
    with open(filename, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str, new_str)
                file_data += line
    f.clse()
    with open(file,"w",encoding="utf-8") as f:
        f.write(file_data)
        f.clse()


def filereplace2(filename):
    old_str = """
    new_str = ""
    with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
        for line in f1:
            f2.write(re.sub(old_str, new_str,line))
    f1.close()
    f2.close()
    os.remove(file)
    os.rename("%s.bak" % file, file)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值