zoukankan      html  css  js  c++  java
  • Python3之OS模块文件操作(摘自网络)

    #-*-coding:utf-8-*-
    __author__ = 'AA'

    import os

    class File(object):

    def __init__(self, pathname):
    self.pathname = pathname

    #删除文件
    def delectFile(self, filename):
    fn = self.pathname + str(filename).strip()
    if os.path.isfile(fn):
    os.remove(fn)
    if(not os.path.isfile(fn)):
    print('*Tips: File: ', fn, ' has been deleted.')
    else:
    print('*Tips: File: ', fn, ' not found.')

    #创建文件
    def createFile(self, filename):
    fn = self.pathname + str(filename).strip()
    if not os.path.isfile(fn):
    open(fn, mode='w', encoding='UTF-8').close()

    #获取文件大小
    def getFileSize(self, filename):
    k_size = round(os.stat(filename).st_size / 1024, 1)
    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(' ', dir)
    for file in files:
    print(' ', file, ' ', self.getFileSize(root+'\'+file))


    #让用户选择操作
    def selectOperation():
    print(' *1.List all directories and files.')
    print('*2.Create file.')
    print('*3.Delete file.')
    print('*4.Exit.')

    s = input("*Please select an operation:")
    return s

    if __name__ == '__main__':
    pathname = input('Input a pathname: ')
    file = File(pathname)
    while True:
    selectNum = selectOperation()
    if selectNum == '1':
    file.listPath()
    elif selectNum == '2':
    fn = input("Input a filename: ")
    file.createFile(fn)
    elif selectNum == '3':
    fn = input("Input a filename: ")
    file.delectFile(fn)
    elif selectNum == '4':
    break;
    原始地址:http://blog.csdn.net/myatlantis/article/details/47376919
  • 相关阅读:
    分布式系统之CAP原理
    分布式缓存一致性哈希算法
    数据库三范式 无重复列 完全依赖主键 属性不依赖非主属性
    二叉树 B-树B+树
    数据库索引 主键 聚集索引 非聚集索引
    数据库水平拆分
    线程池ScheduledThreadPoolExecutor
    线程池之ThreadPoolExecutor
    mybatis一级缓存和二级缓存
    vue框架的搭建
  • 原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/7220685.html
Copyright © 2011-2022 走看看