首页 > 编程语言 > 详细

Python3之OS模块文件操作(摘自网络)

时间:2017-07-22 11:38:31      阅读:309      评论:0      收藏:0      [点我收藏+]
#-*-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(‘\t‘, dir)
for file in files:
print(‘\t‘, file, ‘\t‘, self.getFileSize(root+‘\\‘+file))


#让用户选择操作
def selectOperation():
print(‘\n*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

Python3之OS模块文件操作(摘自网络)

原文:http://www.cnblogs.com/gilgamesh-hjb/p/7220685.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!