day12练习

4.1 封装一个删除文件函数os.remove()
如(例子不准确,需要改正确):
编写函数原则:
1. 函数设计要尽量短小
2. 函数声明要做到合理、简单、易于使用
3. 函数参数设计应该考虑向下兼容(版本迭代~使用)
4. 一个函数只做一件事情,尽量保证函数语句粒度的一致性




import os
"""
需求: 实现文件创建与删除
"""
def filedelect(txt_name):
# 判断是否存在
suffix = ".txt"
f_name = txt_name + suffix
txt_root = os.getcwd()+ '\\test_txt\\'+f_name
try :
os.remove(txt_root)
print("{}删除成功".format(txt_name))
except:
print("{}未找到文件{}".format(txt_root,txt_name))

def new_txt(txt_name):
suffix = ".txt"
f_name = txt_name+suffix
txt_root = os.getcwd() + '\\test_txt\\'
if not os.path.exists(txt_root):
os.makedirs(txt_root)
txt_root += f_name
if not os.path.exists(txt_root):
open(txt_root,"w")
print("{}创建成功".format(txt_name))
else:
print("{}已经存在".format(txt_name))

def main():
while True :
try:
print(os.listdir(os.getcwd() + '\\test_txt\\'))
except:
print("文件夹不存在,请创建文件")
print("操作项目\n1.创建文件2.删除文件3其他输入为退出")
work = input("请输入操作项目\n")
if work == "1":
txt_name = input("请输入添加的文件名称:\n")
new_txt(txt_name)
elif work == "2" :
filname = input("请输入删除的文件名:\n")
filedelect(filname)
else:
break

# 执行程序入口,说白了,程序从这里开始运行
if __name__ == "__main__":
main()






猜你喜欢

转载自www.cnblogs.com/lyy17759893807/p/12007177.html