检查可用盘符
def get_disk_list():# This function will return a list which have accessible disksdisk_list = []for c in string.ascii_uppercase:disk = c+':'if os.path.isdir(disk): # if the dir is exists, add it to the listdisk_list.append(disk)return disk_list
遍历所有文件
def walk_file(file):for root, dirs, files in os.walk(file):# root 表示当前正在访问的文件夹路径# dirs 表示该文件夹下的子目录名list# files 表示该文件夹下的文件list# 遍历文件for f in files:print(os.path.join(root, f))# 遍历所有的文件夹for d in dirs:print(os.path.join(root, d))def main(path):walk_file(path)# os.getcwd() 获取当前工作路径,可以作为参数传入
xls转换为xlsx
import os # 导入系统包import win32com.client as win32 # 将Win32com导入为win32if __name__ == '__main__':fname = os.getcwd() + '\Test.xls' # 获取绝对地址文件名excel = win32.gencache.EnsureDispatch('Excel.Application') # 调用win32wb = excel.Workbooks.Open(fname) # 存为wb对象wb.SaveAs(fname + "x", FileFormat=51) # FileFormat = 51 is for .xlsx extensionwb.Close() # FileFormat = 56 is for .xls extensionexcel.Application.Quit()
互相转换
import win32com.client as win32 # 需安装pywin32import os.pathimport globexcel = win32.gencache.EnsureDispatch('Excel.Application')#简易使用方法#filename = r'E:\xlsx\1.xls'#wb = excel.Workbooks.Open(filename)#wb.SaveAs(filename+'x', FileFormat=51) #FileFormat=51 是 .xlsx 的扩展#wb.Close() #FileFormat=56 是 .xls 的扩展#excel.Application.Quit()def xls2xlsx(xls_path, xlsx_path):# xls_path参数为待转换的xls文件所在文件夹# xlsx_path参数为转换完成的xlsx文件保存文件夹# 当xlsx保存文件夹存在同名原xls时,会弹窗提示是否替换,建议保存至空文件夹path_list = glob.glob(xls_path + '\\*.xls') # 获取文件夹下所有xlsfor file in path_list:filename = os.path.basename(file).replace('.xls', '.xlsx') # 获取文件名wb = excel.Workbooks.Open(file)wb.SaveAs(xlsx_path + '\\' + filename, FileFormat=51) # xlsx为51wb.Close()excel.Application.Quit()print('xls2xlsx转换完成')def xlsx2xls(xlsx_path, xls_path):# xlsx_path参数为待转换的xlsx文件所在文件夹# xls_path参数为转换完成的xls文件保存文件夹# 当xls保存文件夹存在同名原xlsx时,会弹窗提示是否替换,建议保存至空文件夹path_list = glob.glob(xlsx_path + '\\*.xlsx') # 获取文件夹下所有xlsxfor file in path_list:filename = os.path.basename(file).replace('.xlsx', '.xls') # 获取文件名wb = excel.Workbooks.Open(file)wb.SaveAs(xls_path + '\\' + filename, FileFormat=56) # xls为56wb.Close()excel.Application.Quit()print('xlsx2xls转换完成')if __name__ == '__main__':xls_path = r'E:\xlsx\xls'xlsx_path = r'E:\xlsx\xlsx'xls2xlsx(xls_path, xlsx_path)#xlsx2xls(xlsx_path, xls_path)
重命名
rename
import os,sysdef add_prefix_subfolders(path):mark = 'pre'old_names = os.listdir(path)for old_name in old_names:os.rename( os.path.join(path,old_name) , os.path.join(path,mark+old_name) )print(old_name,'has been renamed as ', mark+old_name)if __name__ == '__main__':path = os.getcwd()add_prefix_subfolders(path)
传入path 保护脚本模式
import os,sys #导入模块def rename_subfolders(): #定义函数名称old_names = os.listdir( path ) #取路径下的文件名,生成列表for old_name in old_names: #遍历列表下的文件名if old_name!= sys.argv[0]: #代码本身文件路径,防止脚本文件放在path路径下时,被一起重命名new_name=old_name.replace('test-','test2-') #将原来名字里的‘test’替换为‘test2’os.rename(os.path.join(path,old_name),os.path.join(path,new_name)) #子文件夹重命名print (old_name,"has been renamed successfully! New name is: ",new_name) #输出提示
创建文件夹
import osdef mkdir(path):folder = os.path.exists(path)if not folder: #判断是否存在文件夹如果不存在则创建为文件夹os.makedirs(path) #makedirs 创建文件时如果路径不存在会创建这个路径print "--- new folder... ---"print "--- OK ---"else:print "--- There is this folder! ---"file = "G:\\xxoo\\test"mkdir(file) #调用函数
创立工作区
import oswork_space_path = os.getcwd() + '\DMS_WorkSpace' # Work Space Namedef make_DMS_dir(path):folder = os.path.exists(path)if not folder: #判断是否存在文件夹如果不存在则创建为文件夹os.makedirs(path) #makedirs 创建文件时如果路径不存在会创建这个路径print "Work Space Has Been Created!"else:print "Work Space has already exists"make_DMS_dir(work_space_path) #调用函数
OS 操作
os.listdir(dirname):列出dirname下的目录和文件os.getcwd():获得当前工作目录os.curdir:返回当前目录('.')os.chdir(dirname):改变工作目录到dirnameos.path.isdir(name):判断name是不是一个目录,name不是目录就返回falseos.path.isfile(name):判断name是不是一个文件,不存在name也返回falseos.path.exists(name):判断是否存在文件或目录nameos.path.getsize(name):获得文件大小,如果name是目录返回0Los.path.abspath(name):获得绝对路径os.path.normpath(path):规范path字符串形式os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)os.path.splitext():分离文件名与扩展名os.path.join(path,name):连接目录与文件名或目录os.path.basename(path):返回文件名os.path.dirname(path):返回文件路径os.remove(dir) #dir为要删除的文件夹或者文件路径os.rmdir(path) #path要删除的目录的路径。需要说明的是,使用os.rmdir删除的目录必须为空目录,否则函数出错。os.path.getmtime(name) #获取文件的修改时间os.stat(path).st_mtime#获取文件的修改时间os.stat(path).st_ctime #获取文件创建时间os.path.getctime(name)#获取文件的创建时间
时间戳操作
#endcoding: utf-8# 获取文件的时间属性# 用到的知识# os.getcwd() 方法用于返回当前工作目录# os.path.getatime(file) 输出文件访问时间# os.path.getctime(file) 输出文件的创建时间# os.path.getmtime(file) 输出文件最近修改时间import timeimport osdef fileTime(file):return [time.ctime(os.path.getatime(file)),time.ctime(os.path.getmtime(file)),time.ctime(os.path.getctime(file))]times = fileTime(os.getcwd())print(times)print(type(times))
文件操作
#文件、文件夹的移动、复制、删除、重命名#导入shutil模块和os模块import shutil,os#复制单个文件shutil.copy("C:\\a\\1.txt","C:\\b")#复制并重命名新文件shutil.copy("C:\\a\\2.txt","C:\\b\\121.txt")#复制整个目录(备份)shutil.copytree("C:\\a","C:\\b\\new_a")#删除文件os.unlink("C:\\b\\1.txt")os.unlink("C:\\b\\121.txt")#删除空文件夹try:os.rmdir("C:\\b\\new_a")except Exception as ex:print("错误信息:"+str(ex))#提示:错误信息,目录不是空的#删除文件夹及内容shutil.rmtree("C:\\b\\new_a")#移动文件shutil.move("C:\\a\\1.txt","C:\\b")#移动文件夹shutil.move("C:\\a\\c","C:\\b")#重命名文件shutil.move("C:\\a\\2.txt","C:\\a\\new2.txt")#重命名文件夹shutil.move("C:\\a\\d","C:\\a\\new_d")
工作区设计
长春大学课程表
# -*- coding: utf-8 -*-# Filename:BasicCurriculumInfoimport mathclass CourseUnit:__defaultWorkbook = 0__defaultWorksheet = 0__curriculumArea = 0__static_to_class_m = 0# if your code a tool func and don't want to be static, add this useless statementdef __init__(self, workbook_obj):self.__defaultWorkbook = workbook_objself.__defaultWorksheet = self.__defaultWorkbook.worksheets[0]self.__curriculumArea = self.__defaultWorksheet['B4:H9']# The ADT of B4:H9 consisted by tuple(tuple()) access by [][]def get_curriculums(self): # this is a test funcreturn self.__curriculumAreadef get_duration(self, week, num):week_list_all = []curriculum_string = self.__curriculumArea[num - 1][week - 1].valueif curriculum_string == ' ':return -1if self.__find_all_subs('[周]', curriculum_string) != -1:index_list = self.__find_all_subs('[周]', curriculum_string)newline_list = []num_of_para = len(index_list)for i in index_list:newline_list.append(curriculum_string[0:i].rfind('\n'))week_str = []for i in range(0, num_of_para):week_str.append(curriculum_string[newline_list[i] + 1:index_list[i]])week_string = ""for subs in week_str:for chars in subs:week_string += charsweek_string += ','week_string = week_string.replace(',', '@', 6)week_string = week_string.split('@')week_list = self.__curriculum_expansion(week_string)week_list_all.extend(week_list)if self.__find_all_subs('[双周]', curriculum_string) != -1:index_list = self.__find_all_subs('[双周]', curriculum_string)newline_list = []num_of_para = len(index_list)for i in index_list:newline_list.append(curriculum_string[0:i].rfind('\n'))week_str = []for i in range(0, num_of_para):week_str.append(curriculum_string[newline_list[i] + 1:index_list[i]])week_string = ""for subs in week_str:for chars in subs:week_string += charsweek_string += ','week_string = week_string.replace(',', '@', 6)week_string = week_string.split('@')week_list = self.__curriculum_expansion(week_string)week_list_all.extend(week_list)if self.__find_all_subs('[单周]', curriculum_string) != -1:index_list = self.__find_all_subs('[单周]', curriculum_string)newline_list = []num_of_para = len(index_list)for i in index_list:newline_list.append(curriculum_string[0:i].rfind('\n'))week_str = []for i in range(0, num_of_para):week_str.append(curriculum_string[newline_list[i] + 1:index_list[i]])week_string = ""for subs in week_str:for chars in subs:week_string += charsweek_string += ','week_string = week_string.replace(',', '@', 6)week_string = week_string.split('@')week_list = self.__curriculum_expansion(week_string)week_list_all.extend(week_list)week_list_all.sort()return week_list_alldef __find_all_subs(self, sub, s):self.__static_to_class_m = 0index_list = []index = s.find(sub)while index != -1:index_list.append(index)index = s.find(sub, index + 1)if len(index_list) > 0:return index_listelse:return -1def __str_to_int(self, o_str):self.__static_to_class_m = 0char_list = []for chars in o_str:char_list.append(chars)int_list = []for ints in char_list:int_list.append(int(ints) - int('0'))bit = len(int_list)local_iter = 0integer = 0while bit != 0:integer += int_list[local_iter] * math.pow(10, bit - 1)local_iter += 1bit -= 1return int(integer)def __curriculum_expansion(self, o_str_list):self.__static_to_class_m = 0u_list = []u_start = 0u_end = 0t_list = []for step_len in o_str_list:if step_len == '':continueif '-' in step_len:u_list = step_len.split('-')u_start = u_list[0]u_end = u_list[1]u_start = self.__str_to_int(u_start)u_end = self.__str_to_int(u_end)for i in range(u_start, u_end + 1):t_list.append(i)elif '-' not in step_len:t_list.append(self.__str_to_int(step_len))t_list.sort()return t_listdef __reconnect_lists(self, o_list, t_list):self.__static_to_class_m = 0o_list = o_list.expand(t_list)for chapter in o_list:if chapter.find('*') > 10:o_list.append('*')chapter.reiter_count()elif chapter.thread_max() < 50:t_list.reinsert(chapter.iter.en())
# -*- coding: utf-8 -*-# Filename:BasicCurriculumInfoimport openpyxl as vpaimport reclass StudentSheetInfo:__defaultWorkbook = 0__defaultWorksheet = 0__basicTitle = 0__infoTitle = 0def __init__(self, workbook_obj):self.__defaultWorkbook = workbook_objself.__defaultWorksheet = self.__defaultWorkbook.worksheets[0]self.__basicTitle = self.__defaultWorksheet['A1']self.__infoTitle = self.__defaultWorksheet['A2']def get_class_sheet_name(self):name_position = []for i in range(0, len(self.__basicTitle.value)):if self.__basicTitle.value[i] == ' ':name_position.append(i)return self.__basicTitle.value[name_position[0]+1:name_position[1]]# the format of str: "CollegeName Name Title"def get_class_sheet_school_year(self):school_year_position = re.search('学年学期:', self.__infoTitle.value).span()for i in range(school_year_position[1], len(self.__infoTitle.value)):if self.__infoTitle.value[i] == ' ':end_mark = ibreakreturn self.__infoTitle.value[school_year_position[1]:end_mark]# the format of str: "学年学期:YYYY-YYYY-I ..."def get_class_sheet_class(self):school_year_position = re.search('班级:', self.__infoTitle.value).span()for i in range(school_year_position[1], len(self.__infoTitle.value)):if self.__infoTitle.value[i] == ' ':end_mark = ibreakreturn self.__infoTitle.value[school_year_position[1]:end_mark]# the format of str: "班级:MajorYYNUM ..."def get_class_sheet_major(self):school_year_position = re.search('所属班级:', self.__infoTitle.value).span()for i in range(school_year_position[1], len(self.__infoTitle.value)):if self.__infoTitle.value[i] == ' ':end_mark = ibreakreturn self.__infoTitle.value[school_year_position[1]:end_mark]# the format of str: "所属班级:MajorYYNUM ..."def get_class_sheet_update_time(self):return self.__infoTitle.value[-10:]
新更新
# -*- coding: utf-8 -*-# Filename:BasicCurriculumInfoimport mathclass CourseUnit:__defaultWorkbook = 0__defaultWorksheet = 0__curriculumArea = 0__static_to_class_m = 0# if your code a tool func and don't want to be static, add this useless statementdef __init__(self, workbook_obj):self.__defaultWorkbook = workbook_objself.__defaultWorksheet = self.__defaultWorkbook.worksheets[0]self.__curriculumArea = self.__defaultWorksheet['B4:H9']# The ADT of B4:H9 consisted by tuple(tuple()) access by [][]def get_curriculums(self): # this is a test functionreturn self.__curriculumAreadef get_duration(self, week, num):week_list_all = []curriculum_string = self.__curriculumArea[num - 1][week - 1].valueif curriculum_string == ' ':return -1if self.__find_all_subs('[周]', curriculum_string) != -1:index_list = self.__find_all_subs('[周]', curriculum_string)newline_list = []num_of_para = len(index_list)for i in index_list:newline_list.append(curriculum_string[0:i].rfind('\n'))week_str = []for i in range(0, num_of_para):week_str.append(curriculum_string[newline_list[i] + 1:index_list[i]])week_string = ""for subs in week_str:for chars in subs:week_string += charsweek_string += ','week_string = week_string.replace(',', '@', 20 + 1)week_string = week_string.split('@')week_list = self.__curriculum_expansion(week_string)week_list_all.extend(week_list)if self.__find_all_subs('[双周]', curriculum_string) != -1:index_list = self.__find_all_subs('[双周]', curriculum_string)newline_list = []num_of_para = len(index_list)for i in index_list:newline_list.append(curriculum_string[0:i].rfind('\n'))week_str = []for i in range(0, num_of_para):week_str.append(curriculum_string[newline_list[i] + 1:index_list[i]])week_string = ""for subs in week_str:for chars in subs:week_string += charsweek_string += ','week_string = week_string.replace(',', '@', 6)week_string = week_string.split('@')week_list = self.__curriculum_expansion(week_string)week_list_all.extend(week_list)if self.__find_all_subs('[单周]', curriculum_string) != -1:index_list = self.__find_all_subs('[单周]', curriculum_string)newline_list = []num_of_para = len(index_list)for i in index_list:newline_list.append(curriculum_string[0:i].rfind('\n'))week_str = []for i in range(0, num_of_para):week_str.append(curriculum_string[newline_list[i] + 1:index_list[i]])week_string = ""for subs in week_str:for chars in subs:week_string += charsweek_string += ','week_string = week_string.replace(',', '@', 6)week_string = week_string.split('@')week_list = self.__curriculum_expansion(week_string)week_list_all.extend(week_list)week_list_all.sort()return week_list_alldef __find_all_subs(self, sub, s): # find all substring in stringself.__static_to_class_m = 0index_list = []index = s.find(sub)while index != -1:index_list.append(index)index = s.find(sub, index + 1)if len(index_list) > 0:return index_list # return location indexelse:return -1 # return -1 if nothing have founddef __str_to_int(self, o_str): # convert a string type number to intself.__static_to_class_m = 0char_list = []for chars in o_str:char_list.append(chars)int_list = []for ints in char_list:int_list.append(int(ints) - int('0'))bit = len(int_list)local_iter = 0integer = 0while bit != 0:integer += int_list[local_iter] * math.pow(10, bit - 1)local_iter += 1bit -= 1return int(integer)def __curriculum_expansion(self, o_str_list): # get a string with ',' and expand itself.__static_to_class_m = 0t_list = []for step_len in o_str_list:if step_len == '':continueif '-' in step_len:u_list = step_len.split('-')u_start = u_list[0]u_end = u_list[1]u_start = self.__str_to_int(u_start)u_end = self.__str_to_int(u_end)for i in range(u_start, u_end + 1):t_list.append(i)elif '-' not in step_len:t_list.append(self.__str_to_int(step_len))t_list.sort()return t_listdef get_curriculum_layout(self): # convert list to a binary number (int)layout = []for week in range(1, 7 + 1): # 7 days a week and a boundfor chapter in range(1, 6 + 1): # 6 lesson a day and a boundlayout.append(self.list_to_binary(self.get_duration(week, chapter)))return layout@staticmethoddef list_to_binary(o_list):m_binary = 0if o_list == -1: # runtime datatype double check, (Customized)return -1for it in o_list:m_binary += 2 ** itreturn m_binary@staticmethoddef binary_to_list(o_bin):const_bit = 0b1m_list = []for it in range(0, 20):ret = o_bin & const_bit # get last bitif ret == 1:m_list.append(it)o_bin = o_bin >> 1return m_list"""Excel cannot convert a list data type to a table data type.However, the list is not repeated, so I can use binarydistribution to represent the contents of the list.for example i have a list which is [2, 3, 5]i cannot put it into excel cells, but i can transferthis list into a number which is 0b1011000 b 1 0 1 1 0 0^ ^ ^5 3 2and this number is 44 (int)"""
# -*- coding: utf-8 -*-# Filename:BasicCurriculumInfo"""class provides basic information of curriculum tablemost of method may not used in actual practicethe variable 'end_mark' is local variable, ignoresome warnings below:"Local variable 'end_mark' might be referenced before assignment"DO NOT ADD GLOBAL STATEMENTS"""import reclass StudentSheetInfo:__defaultWorkbook = 0__defaultWorksheet = 0__basicTitle = 0__infoTitle = 0def __init__(self, workbook_obj):self.__defaultWorkbook = workbook_objself.__defaultWorksheet = self.__defaultWorkbook.worksheets[0]self.__basicTitle = self.__defaultWorksheet['A1']self.__infoTitle = self.__defaultWorksheet['A2']def get_class_sheet_name(self):name_position = []for i in range(0, len(self.__basicTitle.value)):if self.__basicTitle.value[i] == ' ':name_position.append(i)return self.__basicTitle.value[name_position[0]+1:name_position[1]]# the format of str: "CollegeName Name Title"def get_class_sheet_school_year(self):school_year_position = re.search('学年学期:', self.__infoTitle.value).span()for i in range(school_year_position[1], len(self.__infoTitle.value)):if self.__infoTitle.value[i] == ' ':end_mark = ibreakreturn self.__infoTitle.value[school_year_position[1]:end_mark]# the format of str: "学年学期:YYYY-YYYY-I ..."def get_class_sheet_class(self):school_year_position = re.search('班级:', self.__infoTitle.value).span()for i in range(school_year_position[1], len(self.__infoTitle.value)):if self.__infoTitle.value[i] == ' ':end_mark = ibreakreturn self.__infoTitle.value[school_year_position[1]:end_mark]# the format of str: "班级:MajorYYNUM ..."def get_class_sheet_major(self):school_year_position = re.search('所属班级:', self.__infoTitle.value).span()for i in range(school_year_position[1], len(self.__infoTitle.value)):if self.__infoTitle.value[i] == ' ':end_mark = ibreakreturn self.__infoTitle.value[school_year_position[1]:end_mark]# the format of str: "所属班级:MajorYYNUM ..."def get_class_sheet_update_time(self):return self.__infoTitle.value[-10:]
