Python文件操作系统开发实验
一、实验要求:
- 默认进入当前工作目录中。并且把目录中的内容(文件跟文件夹)进行输出。每个内容前需要加上序号。如果是文件夹的话需要在名字前加上\
- 用户可以进行输入文件序号
- 用户选择的序号如果是文件夹则打开该目录并且输出该目录下的内容
- 用户选择的序号如果是文件则把该文件的内容输出
- 用户如果选择的是目录,则在该目录下继续之前的操作
- 用户选择的是文件,输出内容后,返回到当目录操作
进阶要求:
- 用户除了输入序号外,还可以输入特殊字符进行操作。比方:'..':返回上级目录。'~':返回默认工作目录
- 用户可以使用命令模式进行文件的操作。比如:
- '-r 文件序号': 把该序号的文件删除
- '-c 文件序号 文件路径': 把文件序号中的文件复制到路径中
- '-m': 进入文件创建模式
- '-up 文件序号': 进入文件更新模式。选择文件内容输出,并且让用户输入追加的内容
二、实验步骤:
1. 编写代码:
import os
from shutil import copy
#定义一个文件系统主函数
def dirSystem(path):
# 定义一个输出目录列表的函数
def showDirList(file_lst, path):
listLen = len(file_lst)
print('='*15+'目录"'+path+'"的内容列表'+'='*15)
#根目录则输出这条
if(path==os.getcwd()):
print('这是根目录了')
#否则输出这条
else:
print('../: 返回上一层')
# 遍历输出目录列表
for d,i in zip(file_lst, range(listLen)):
if os.path.isdir(path+'\\'+d):
i=i+1
print(i,':','\\'+d)
else:
i=i+1
print(i,':', d)
else:
#添加退出程序选项
print(len(file_lst)+1,': 退出')
print('='*15+'文件列表结束'+'='*15)
# 1.2 获取工作目录下所有内容信息
file_lst = os.listdir(path)
# 2 调用输出目录列表的函数
showDirList(file_lst, path)
# 3.1 用户输入
o1=str(input('请输入选择序号或操作代码:'))
if o1.isdigit():
o = int(o1)
listLen =len(file_lst)
#判断选项是否是关闭程序
if listLen+1 == o:
print('关闭程序')
exit()
#否则继续执行打开文件
elif (o<listLen and o>0) or (listLen==1 and o==1):
# 3.2 通判断用户输入的序号的文件是否为文件夹,然后使用不同的方法打开
if os.path.isdir(path+'\\'+file_lst[o-1]):
# 对操作目录进行重新赋值
path= path+'\\'+file_lst[o-1]
# 4.2 如果用户输入的序号是一个文件夹,则把该目录中的内容打印出来
file_lst=os.listdir(path)
# 因为用户选择的是一个文件夹,所以需要继续之前的操作
dirSystem(path)
else:
#读取文件并打开
with open(path+'\\'+file_lst[o-1],encoding='gbk') as f:
print(f.read())
#读取完毕返回当前目录
dirSystem(path)
else:
print('='*15+'操作错误请重试'+'='*15)
dirSystem(path)
else:
#判断选项是否是返回上级
if o1=='..':
#查找路径中最后一个'\'的位置
pInt = path.rfind('\\')
#截取上级目录
path = path[0:pInt]
print('='*15+'正在返回上级'+'='*15)
#返回最初
dirSystem(path)
elif o1=='~':
#返回最初路径
dirSystem(os.getcwd())
#删除操作
elif o1.find('-r')!=-1 and o1[3:len(o1)].isdigit():
o = int(o1[3:len(o1)])
if os.path.isdir(path+'\\'+file_lst[o-1]):
os.rmdir(path+'\\'+file_lst[o-1])
print('删除完成')
dirSystem(path)
else:
os.remove(path+'\\'+file_lst[o-1])
print('删除完成')
dirSystem(path)
#追加操作
elif o1.find('-up')!=-1 and o1[4:len(o1)].isdigit():
o = int(o1[3:len(o1)])
with open(path+'\\'+file_lst[o-1],"a") as f:
zjStr=str(input('请输入追加的文本:'))
f.write(zjStr)
print('追加完成')
dirSystem(path)
elif o1=='-m':
zjStr=path+'\\'+str(input('请输入要创建的文件名'))
with open(zjStr,"w") as f:
xrStr=str(input('请输入写入的内容:'))
f.write(xrStr)
print('创建完成')
dirSystem(path)
#and o1.count(' ')==2
elif o1.find('-c')!=-1 and o1[3:o1.rfind(' ')][0:o1.rfind(' ')].isdigit():
o = int(o1[3:o1.rfind(' ')][0:o1.rfind(' ')])
lj = o1[o1.rfind(' ')+1:len(o1)]
if os.path.isdir(lj) and os.path.exists(lj):
copy(path+'\\'+file_lst[o-1],lj)
print('拷贝完成')
dirSystem(path)
else:
print('='*15+'操作错误请重试'+'='*15)
dirSystem(path)
else:
print('='*15+'操作错误请重试'+'='*15)
dirSystem(path)
#路径赋初始值
path = os.getcwd()
#调用文件管理系统方法
dirSystem(path)