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)