理解并掌握文件操作和目录操作的相关方法,以及二进制文件的序列化和反序列化方法。能够熟练应用os模块和os.path模块进行文件和目录操作。
Console
熊大
熊二
笨笨
{‘熊大’: 60, ‘熊二’: 70, ‘笨笨’: 80}
import pickle a='熊大' b='熊二' c='笨笨' dic={'熊大':60,'熊二':70,'笨笨':80} data=(a,b,c,dic) with open('pickle.date','wb') as f: try: pickle.dump(len(data),f) for item in data: pickle.dump(item,f) except: print('写文件异常') with open('pickle.date','rb') as f: n=pickle.load(f) for i in range(n): x=pickle.load(f) print(x)
import os os.getcwd()
Console:
‘C:\Python34’
os.chdir(r'c:\\') os.getcwd()
Console:
‘c:\’
>>> os.chdir(r'c:\Python34') >>> os.getcwd()
Console:
‘c:\Python34’
Console:
folder path:D:
file path:新建文本文档.txt
D:\QQDownload\新建文本文档.txt
import os def search_currentfolder(folder, filename): try: files = os.listdir(folder) except: print(folder,"文件访问否认") return None if files.__contains__(filename): return os.path.join(folder, filename) else: return None def search_allfolder(folder, filename): filepath = search_currentfolder(folder,filename) if filepath: return filepath else: try: files = os.listdir(folder) except: return None folders = list(map(lambda name:folder+"\\"+name, filter(lambda path: not path.__contains__("."), files))) if not folders: return None for folderpath in folders: if os.path.isdir(folderpath): filepath = search_allfolder(folderpath, filename) if filepath: return filepath return None def search(folder,filename,model="current"): if model=="all": filepath = search_allfolder(folder,filename) else: filepath = search_currentfolder(folder, filename) if filepath: print(filepath) else: print("否") folder = input("folder path:") filename = input("file path:") search(folder,filename,model = "all")