首页 > 代码库 > Python8-24

Python8-24

pickle存取图片

#Open your images in binary mode and read them in as binary strings then#save them in a list/dict/tuple , then pickle it.>>> import Image, pickle, cStringIO>>> i = open(c:/1.jpg, rb)>>> i.seek(0)>>> w = i.read()>>> i.close()>>> dic =  {1:w,2:w,3:w,4:w}>>> p = pickle.dumps(dic)# storage would happen at this point#Ok now you take your pickled string and unpickle your object and select#the item you want and put it in a cStringIO or StringIO so we can open#it directly with PIL.# sometime in the future>>> o = pickle.loads(p)>>> one_im = o[1]>>> c = StringIO.StringIO()>>> c.write(one_im)>>> c.seek(0)>>> im = Image.open(c)>>> im.show()#Alternatively you can create a StringIO object and pickle that in your#dictionary so you can just load it later with PIL.

This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files). See the description of file objects for operations (section File Objects). (For standard strings, see str and unicode.)

 

#拆分目录与文件os.path.split()#连接目录与文件os.path.join(path,name)#返回文件名os.path.basename(path)#返回路径os.path.dirname(path)

遍历目录

import os,sysdef listdir(dir,file):    file.write(dir + \n)    fielnum = 0    list = os.listdir(dir)  #列出目录下的所有文件和目录    for line in list:        filepath = os.path.join(dir,line)        if os.path.isdir(filepath):  #如果filepath是目录,则再列出该目录下的所有文件            myfile.write(    + line + \\+\n)            for li in os.listdir(filepath):                myfile.write(     +li + \n)                fielnum = fielnum + 1        elif os.path:   #如果filepath是文件,直接列出文件名            myfile.write(   +line + \n)            fielnum = fielnum + 1    myfile.write(all the file num is + str(fielnum))dir = raw_input(please input the path:)myfile = open(list.txt,w)
‘‘‘os.walk方法os模块提供的walk方法很强大,能够把给定的目录下的所有目录和文件遍历出来。方法:os.walk(path),遍历path,返回一个对象,他的每个部分都是一个三元组,(‘目录x‘,[目录x下的目录list],目录x下面的文件)‘‘‘import osdef walk_dir(dir,fileinfo,topdown=True):    for root, dirs, files in os.walk(dir, topdown):        for name in files:            print(os.path.join(name))            fileinfo.write(os.path.join(root,name) + \n)        for name in dirs:            print(os.path.join(name))            fileinfo.write(   + os.path.join(root,name) + \n)dir = raw_input(please input the path:)fileinfo = open(list.txt,w)walk_dir(dir,fileinfo)‘‘‘topdown决定遍历的顺序,如果topdown为True,则先列举top下的目录,然后是目录的目录,依次类推,反之,则先递归列举出最深层的子目录,然后是其兄弟目录,然后子目录。‘‘‘

 

Python8-24