实验目的:
理解并掌握文件操作和目录操作的相关方法,以及二进制文件的序列化和反序列化方法。能够熟练应用os模块和os.path模块进行文件和目录操作。
实验内容:
- 使用pickle模块将包含学生成绩的字典保存为二进制文件,然后再读取内容并显示。
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)
- 编写代码,将当前工作目录修改为“C:\”,并验证,最后将当前工作目录恢复为原来的目录。
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")
|