Python3之OS模块文件操作(摘自网络)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(‘\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模块文件操作(摘自网络)的主要内容,如果未能解决你的问题,请参考以下文章