python学习--标准库之os 实例(1)
#!/usr/bin/env python3 #-*-coding:utf-8-*- import os class File(object): def __init__(self, pathname): self.pathname = pathname #删除文件 def delectFile(self, filename): #fn = self.pathname + str(filename).strip() #用上一语句不能正确获取文件名 fn = os.path.join(self.pathname, str(filename).strip()) #if os.path.isfile(fn): #判断一个文件是否存在 if os.access(fn, os.F_OK): os.remove(fn) if(not os.path.isfile(fn)): #如果文件不存在了 #print('*Tips: File: ', fn, ' has been deleted.') print('*注意:文件"{}"已删除'.format(fn)) else: #print('*Tips: File: ', fn, ' not found.') print('注意:文件"{}"未找到'.format(fn)) #创建文件 def createFile(self, filename): #fn = self.pathname + str(filename).strip() fn = os.path.join(self.pathname, str(filename).strip()) print(fn) if not os.path.isfile(fn): open(fn, mode='w', encoding='UTF-8').close() print('注意:文件"{}"已创建成功!'.format(fn)) #获取文件大小 def getFileSize(self, filename): k_size = round(os.stat(filename).st_size / 1024, 1) #os.stat(filename)可以返回文件的属性 if k_size > 1024: m_size = round(k_size / 1024, 1) if m_size > 1024: return str(round(m_size / 1024, 1)) + 'G' else: return str(m_size) + 'M' else: return str(k_size) + 'K' #列出目录下所有文件夹和文件 def listPath(self): for root, dirs, files in os.walk(self.pathname): print(root) for dir in dirs: print('\t', dir) for file in files: print('\t', file, '\t', self.getFileSize(root+'\\'+file)) #让用户选择操作 def selectOperation(): print('\n*1.列出目录下所有文件夹和文件.') print('*2.创建文件.') print('*3.删除文件.') print('*4.退出.') s = input("*请选择一个操作:") return s if __name__ == '__main__': pathname = input('请输入一个目录名: ') file = File(pathname) while True: selectNum = selectOperation() if selectNum == '1': file.listPath() elif selectNum == '2': fn = input("输入一个文件名: ") file.createFile(fn) elif selectNum == '3': fn = input("输入一个文件名: ") file.delectFile(fn) elif selectNum == '4': break;