python学习

来源:互联网 发布:php获取本机ip 编辑:程序博客网 时间:2024/06/05 22:18

文件操作

1.判断文件/创建/删除等操作

import os#可使用此方法判断文件or目录是否存在os.path.exists(filepath)os.path.isfile()os.path.isdir()#多级的话,只创建最后一级,若上级不存在,抛异常os.makedir()#递归创建os.makedirs()#删除文件os.remove()

2.读/写文件1

input = open('data', 'r')#读所有内容text = input.read()#读每行list_of_all_the_lines = input.readlines()for line in file_object:    process line#写文件-英文f = file('a.txt', 'w')f.write('eng')f.colse()#写文件-中文-UTF8import codecsf = codecs.open("b.txt", "w", "utf-8")f.write('中文')f.close()

3.生成文件md52

import hashlibfileobject = open(filename,"r")  fText = fd.read()  fileobject.close()           fmd5 = hashlib.md5(fText)md5 = fmd5.hexdigest()  

4.获取当前脚本文件路径3

import syspath = sys.path[0]

python操作redis4

import redisr = redis.StrictRedis(host='127.0.0.1', port=6379)r.set('key', 'val')res = r.get('key')

python下载文件5

import urlliburlretrieve(url, [filename=None, [reporthook=None, [data=None]]])

python json处理

import jsondata = [{'a':"1",'b':(0,1),'c':3.0}]str = json.dumps(data)data = json.loads(str)

python bsdiff4

首先安装模块bsdiff4

import bsdiff4fileObjectA = open(sourceFilePath, 'r')textA = fileObjectA.read()fileObjectA.close()fileObjectB = open(fileBPath, 'r')textB = fileObjectB.read()fileObjectB.close()#生成patchpatch = bsdiff4.diff(textA, textB)#根据patch生成新文件newFile = bsdiff4.patch(textA, patch)

  1. http://www.cnblogs.com/allenblogs/archive/2010/09/13/1824842.html ↩
  2. http://blog.csdn.net/linda1000/article/details/17581035 ↩
  3. http://www.cnblogs.com/pchgo/archive/2011/09/19/2181248.html ↩
  4. http://blog.csdn.net/chosen0ne/article/details/7319807 ↩
  5. http://www.open-open.com/lib/view/open1430982247726.html ↩
0 0
原创粉丝点击