• 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
  • 相关阅读:
    显著提升程序员身心健康和工作效率的装备有哪些?
    谁控制了我们的浏览器?
    利用Http Authentication Url+csrf劫持路由器DNS
    如​何​删​除​G​P​T​保​护​分​区
    Linux定时器的使用
    缺少 mcrypt 扩展。请检查 PHP 配置。(phpmyadmin)
    xxx is not in the sudoers file
    linux mysql 找不到 <mysql/mysql.h>
    C++面试常见问题(持续更新)
    代码模板(new)
  • 原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/7220685.html
Copyright © 2020-2023  润新知