目录
一、简介
二、思路及程序所创建内容的特性
三、程序源代码
(1)调用Python内置库
(2)定义函数1:创建模式1(各章的小节数完全一致)
(3)定义函数2:创建模式2(大部分章中小节数一致)
(4)定义函数3:创建模式3(自定义各章小节数)
(5)定义函数4:保留模式1
(6)定义函数5:保留模式2
(7)定义函数6:保留模式3
(8)选择结构1:调用主函数(创建函数)
(9)选择结构2:调用副函数(保留函数)和选择结束语
四、灵感和缺陷
一、简介
在用到计算机的日常生活和学习中,可能会碰到连续性地创建围绕某个主题的目录、文件,本文将要介绍一个辅助类程序(笔者突发奇想写下来的)。
本程序适用于MacOs平台。
二、思路及程序所创建内容的特性
先听我画大饼:
在学习某Python教材时,我发现其中需要完成的练习程序颇多且命名、格式都有规律,所以在启发下完成这个程序。
这个程序包含三个主函数,三个副函数。主函数负责创建章回式目录、文件,副函数负责新建包含本次操作选择的主函数的Python脚本。
这个程序会以提问的形式与使用者交互,获取关键信息,如主题、章节数量、章节关系等,随后根据获取到的信息使用不同的函数。最终,我还很“贴心”地添加了“是否保留设置”的提问,实质上就是根据三个主函数的选择创建新Python脚本,方便下一次使用。
注:(1)这里的“主函数”不是C语言术语,“副函数”也不是Java术语,这两个仅仅表示主要和次要的功能关系。
注:(2)通过调用副函数生成的Python脚本中还会包含一份以绝对路径书写的文件列表。
下文,我会再述灵感和思路。
这个程序的产物有几个显著特性:
1)内容连续性
2)组织性(以类似章回体的形式)
三、程序源代码
下面是正式版代码,因为过长而不好解析,所以我将内置函数一个一个排列开:
(1)调用Python内置库
本程序需要两个库:os和time。os库用来创建目录,time是最后的点缀,需要它来根据时间选择结束语。
import os import time as t
(2)定义函数1:创建模式1(各章的小节数完全一致)
这个函数默认各个章回中小节数相同。以此创建对应输入的目录和文件。
def mode_all_same():
global file_list_1
chapter=int(input("What's the last chapter? >>[").strip())+1
section_num=int(input('How many sections are there in each chapter? >>[').strip())+1
section_list=[]
file_list_1=[]
chapter_list=[]
Error_count=0
for i in range(section_num):
section_list.append(i)
section_list.pop(0)
for i in range(chapter):
chapter_list.append(i)
chapter_list.pop(0)
for chapter in chapter_list:
for section in section_list:
path=f'{directory}/{key_wd}/{key_wd}_{chapter}/{key_wd}_{chapter}_{section}{format_}'
try:
try:
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_1.append(path)
except FileNotFoundError:
try:
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_1.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileNotFoundError:
directory_=f'{directory}/{key_wd}'
os.mkdir(directory_)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_1.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileExistsError:
Error_count+=1
print(f'Error[{Error_count}]:File already exists. NameCode:{chapter}.{section}')
file_list_1.append(path)
print('nYour creat command has already done.','Here is the file list:',sep='n')
for file in file_list_1:
print(f't{file}')
(3)定义函数2:创建模式2(大部分章中小节数一致)
这个函数默认小节数相同的章回占大部分。
def mode_choose_same():
global file_list_2
same_ch_list=[0]
dif_ch_list=[0]
dif_sec_list=[0]
section_same_list=[]
file_list_2=[]
Error_count=0
while same_ch_list[-1]!='!':
same_ch_list.append(input('Please key in the same chapters one by onen(only takes the most)(put a "!" in list when all in place). >>[').strip())
section_same_num=int(input('How many sections are there in each then? >>[').strip())+1
print('Please key in other chapters and their section numbers one by onen(only takes one integer at a time)(put a "!" in list twice when all in place).')
while dif_sec_list[-1]!='!':
dif_ch_list.append(input('chapter >>[').strip())
dif_sec_list.append(input('section(s) >>[').strip())
same_ch_list.pop(0);same_ch_list.pop(-1)
dif_ch_list.pop(0);dif_ch_list.pop(-1)
dif_sec_list.pop(0);dif_sec_list.pop(-1)
dif_list=list(zip(dif_ch_list,dif_sec_list))
for i in range(section_same_num):
section_same_list.append(i)
section_same_list.pop(0)
for chapter in same_ch_list:
for section in section_same_list:
path=f'{directory}/{key_wd}/{key_wd}_{chapter}/{key_wd}_{chapter}_{section}{format_}'
try:
try:
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_2.append(path)
except FileNotFoundError:
try:
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_2.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileNotFoundError:
directory_=f'{directory}/{key_wd}'
os.mkdir(directory_)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_2.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileExistsError:
Error_count+=1
print(f'Error[{Error_count}]:File already exists. NameCode:{chapter}.{section}')
file_list_2.append(path)
for (chapter,section_num) in dif_list:
section_dif_list=[]
for i in range(int(section_num)+1):
section_dif_list.append(i)
section_dif_list.pop(0)
for section in section_dif_list:
path=f'{directory}/{key_wd}/{key_wd}_{chapter}/{key_wd}_{chapter}_{section}{format_}'
try:
try:
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_2.append(path)
except FileNotFoundError:
try:
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_2.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileNotFoundError:
directory_=f'{directory}/{key_wd}'
os.mkdir(directory_)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_2.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileExistsError:
Error_count+=1
print(f'Error[{Error_count}]:File already exists. NameCode:{chapter}.{section}')
file_list_2.append(path)
print('nYour creat command has already done.','Here is the file list:',sep='n')
file_list_2.sort()
for file in file_list_2:
print(f't{file}')
(4)定义函数3:创建模式3(自定义各章小节数)
这个函数是“名副其实”的DIY函数,需要使用者逐个输入章节和对应的小节数。
def mode_self_choose():
global file_list_3
dif_ch_list=[0]
dif_sec_list=[0]
file_list_3=[]
Error_count=0
print('Please key in the chapters and their section numbers one by onen(only takes one integer at a time)(put a "!" in list twice when all in place).')
while dif_sec_list[-1]!='!':
dif_ch_list.append(input('chapter >>[').strip())
dif_sec_list.append(input('section(s) >>[').strip())
dif_ch_list.pop(0);dif_ch_list.pop(-1)
dif_sec_list.pop(0);dif_sec_list.pop(-1)
dif_list=list(zip(dif_ch_list,dif_sec_list))
for (chapter,section_num) in dif_list:
section_dif_list=[]
for i in range(int(section_num)+1):
section_dif_list.append(i)
section_dif_list.pop(0)
for section in section_dif_list:
path=f'{directory}/{key_wd}/{key_wd}_{chapter}/{key_wd}_{chapter}_{section}{format_}'
try:
try:
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_3.append(path)
except FileNotFoundError:
try:
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_3.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileNotFoundError:
directory_=f'{directory}/{key_wd}'
os.mkdir(directory_)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
directory_=f'{directory}/{key_wd}/{key_wd}_{chapter}'
os.mkdir(directory_)
with open(path,'x') as f:
f.write(f'#{key_wd} {chapter}.{section}')
f.close()
file_list_3.append(path)
Error_count+=1
print(f"Error[{Error_count}]:nThe directory:'{directory_}' used not to exist.")
except FileExistsError:
Error_count+=1
print(f'Error[{Error_count}]:File already exists. NameCode:{chapter}.{section}')
file_list_3.append(path)
print('nYour creat command has already done.','Here is the file list:',sep='n')
file_list_3.sort()
for file in file_list_3:
print(f't{file}')
(5)定义函数4:保留模式1
这个函数会在目标目录(程序创建好的)创建对应的Python脚本文件,写入第一个主函数和必要的选择结构。
def write_mode_1():
dealing=[]
result='nimport osnimport time as tn'
count=0
with open('writer.py','r') as f:
lines=f.readlines()
for l in lines:
dealing.append(l)
count+=1
if l=='def mode_all_same():n':
low=count-1
if l=='def mode_choose_same():n':
high=count-1
for i in range(low,high):
result+=dealing[i]
count=0
for l in lines:
count+=1
if l=='key_wd=input("What's your key word? >>[")n':
low=count-1
for i in range(low,low+3):
result+=dealing[i]
result+='mode_all_same()nn#Here is the file list last time.n#registered time see headern#List:'
for file in file_list_1:
result+=f'n#t{file}'
return result
(6)定义函数5:保留模式2
此函数功能同上,不过对应内容为第二个主函数。
def write_mode_2():
dealing=[]
result='nimport osnimport time as tn'
count=0
with open('writer.py','r') as f:
lines=f.readlines()
for l in lines:
dealing.append(l)
count+=1
if l=='def mode_choose_same():n':
low=count-1
if l=='def mode_self_choose():n':
high=count-1
for i in range(low,high):
result+=dealing[i]
count=0
for l in lines:
count+=1
if l=='key_wd=input("What's your key word? >>[")n':
low=count-1
for i in range(low,low+3):
result+=dealing[i]
result+='mode_choose_same()nn#Here is the file list last time.n#registered time see headern#List:'
for file in file_list_2:
result+=f'n#t{file}'
return result
(7)定义函数6:保留模式3
此函数亦然,对应内容为第三个主函数。
def write_mode_3():
dealing=[]
result='nimport osnimport time as tn'
count=0
with open('writer.py','r') as f:
lines=f.readlines()
for l in lines:
dealing.append(l)
count+=1
if l=='def mode_self_choose():n':
low=count-1
if l=='def write_mode_1():n':
high=count-1
for i in range(low,high):
result+=dealing[i]
count=0
for l in lines:
count+=1
if l=='key_wd=input("What's your key word? >>[")n':
low=count-1
for i in range(low,low+3):
result+=dealing[i]
result+='mode_self_choose()nn#Here is the file list last time.n#registered time see headern#List:'
for file in file_list_3:
result+=f'n#t{file}'
return result
(8)选择结构1:调用主函数(创建函数)
这个结构应该一目了然,通过输入来赋值关键信息,选择主函数。
key_wd=input("What's your key word? >>[")
format_=input('What format do you need for your files?n(plain text format)(e.g.:.txt)>>[')
directory=input('Which directory do you choose to save your work?n(need an abs-path)>>[')
choice=input('Do the chapters which had the same number of sections reach half of the total?n(T/F or 1/0)>>[')
if 'T' in choice or '1' in choice:
choice=input('Does each chapter have same number of sections? (T/F or 1/0)>>[').strip()
if 'T' in choice or '1' in choice:
mode_all_same()
mode=1
else:
mode_choose_same()
mode=2
else:
mode_self_choose()
mode=3
(9)选择结构2:调用副函数(保留函数)和选择结束语
这个结构可有可无,但出于方便还是放里面了。通过这个结构,最终决定是否保留设置,创建包含选择的主函数的Python脚本。(当然,还有礼貌的告别语。)
choice=input("Do you want to remain the settings this time?nI'll make you a new Python programme.n(T/F or 1/0)>>[")
if 'T' in choice or '1' in choice:
year,mon,day,hour,min_,s,wday,yday,isdst=t.localtime()
mon_dict={'1':'Jan','2':'Feb','3':'Mar','4':'Apr','5':'May','6':'Jun',
'7':'Jul','8':'Aug','9':'Sept','10':'Oct','11':'Nov','12':'Dec'}
try:
with open(f'{directory}/{key_wd}/writer.py','x') as f:
f.write(f'#Remain the settings on {day} {mon_dict[str(mon)]},{year}(at{hour}:{min_})n#Please use this file for the same settings next time.')
if mode==1:
f.write(write_mode_1())
elif mode==2:
f.write(write_mode_2())
elif mode==3:
f.write(write_mode_3())
else:
f.close()
f.close()
filename=f'{directory}/{key_wd}/writer.py'
except FileExistsError:
with open(f'{directory}/{key_wd}/writer_{hour}_{min_}_{s}.py','x') as f:
f.write(f'#Remain the settings on {day} {mon_dict[str(mon)]},{year}(at{hour}:{min_})n#Please use this file for the same settings next time.')
if mode==1:
f.write(write_mode_1())
elif mode==2:
f.write(write_mode_2())
elif mode==3:
f.write(write_mode_3())
else:
f.close()
f.close()
filename=f'{directory}/{key_wd}/writer_{hour}_{min_}_{s}.py'
if hour>20:
if min_>=30:
print(f'The settings have been remained in file:n{filename}nThanks for using!nWish you a good night!')
else:
print(f'The settings have been remained in file:n{filename}nThanks for using!nWish you a good day!')
else:
print(f'The settings have been remained in file:n{filename}nThanks for using!nWish you a good day!')
else:
print('Good Bye!')
四、灵感和缺陷
写这个程序之前,就如我在简介中说的一样,学习某教材时做程序练习嫌麻烦,就利用Python搭建了一个小工具,可以根据章节数调整创建新文件。(这个文件我会放在另外起草的一篇中,和本程序的中文版本一起。)
最后说说必不可少的缺陷。有感兴趣的大佬和同行者使用后必定会发现,关键词的提问会很繁琐,而且一些针对回答失误的预防措施也没有完全做到位(如str的strip()方法,try结构等),所以使用的时候会不得不先小心谨慎地检查输入,再按下return键。此外,语言上可能也有一些累赘和繁琐;功能上也有狭窄之处,应用范围和适用场景也并不很多。但这只是一个起步(当然如果写得太糟也可以当作反面教材),来日方长。
在自我检查和IDLE“温馨”的提示下,我已经修补了一些明显的缺陷和错误,但毕竟“明招易躲,暗箭难防”,万望大佬和同行者们不吝笔墨地斧正!



