模块练习

    小程序:根据用户输入选择可以完成以下功能:
    创意文件,如果路径不存在,创建文件夹后再创建文件
    能够查看当前路径
    在当前目录及其所有子目录下查找文件名包含指定字符串的文件


1
import os 2 def currentdir(): 3 return os.getcwd() 4 5 def writefile(inputfile): 6 #r"test\test1\b.txt" 7 fullpath = os.path.join(currentdir,inputfile ) 8 full_dir = os.path.dirname(fullpath) 9 if not os.path.exists(full_dir): 10 os.makedirs(full_dir) 11 filename1 = os.path.basename(fullpath) 12 with open(fullpath,'w+',encoding = 'utf-8') as f_write: 13 f_write.write('test1file\n') 14 f_write.write('dfile\n') 15 f_write.write('best\n') 16 def getfile(inputfile): 17 fullpath = os.path.join(currentdir, inputfile) 18 if not os.path.exists(fullpath): 19 writefile(input_path) 20 print("当前路径为:", os.path.dirname(fullpath)) 21 with open(fullpath, 'r+', encoding='utf-8') as f_read: 22 for i in f_read: 23 print(i.strip('\n')) 24 print("当前路径为:",os.path.dirname(fullpath)) 25 def searchfile(inputfile,content): 26 ser_content = input("search content") 27 fullpath = os.path.join(currentdir, inputfile) 28 for res in os.listdir(os.path.dirname(fullpath)): 29 30 st1 = inputfile.split(os.sep) 31 pst1 = os.sep.join(st1[:-1]) 32 new_fullpath = os.path.join(currentdir,pst1,res) 33 34 with open(new_fullpath, 'r+', encoding='utf-8') as f_read: 35 for i in f_read: 36 if ser_content in i: 37 print(new_fullpath) 38 else: 39 print('nothing') 40 currentdir = currentdir() 41 while True: 42 input_path = input("请输入路径>>>") 43 cmd_dict = {"getfile": getfile, "writefile": writefile, "searchfile":searchfile} 44 for fun in cmd_dict: 45 print (fun) 46 opt = input("请输入:>>>") 47 if opt in cmd_dict: 48 if not os.path.exists(os.path.join(currentdir, input_path)): 49 cmd1 = cmd_dict.get(opt) 50 cmd1(input_path) 51 elif opt == 'searchfile': 52 searchfile(input_path,'file') 53 54 else:continue 55 continue

 

posted @ 2017-04-27 01:17  福临  阅读(204)  评论(0编辑  收藏  举报