检查可用盘符
def get_disk_list():
# This function will return a list which have accessible disks
disk_list = []
for c in string.ascii_uppercase:
disk = c+':'
if os.path.isdir(disk): # if the dir is exists, add it to the list
disk_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导入为win32
if __name__ == '__main__':
fname = os.getcwd() + '\Test.xls' # 获取绝对地址文件名
excel = win32.gencache.EnsureDispatch('Excel.Application') # 调用win32
wb = excel.Workbooks.Open(fname) # 存为wb对象
wb.SaveAs(fname + "x", FileFormat=51) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
互相转换
import win32com.client as win32 # 需安装pywin32
import os.path
import glob
excel = 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') # 获取文件夹下所有xls
for 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为51
wb.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') # 获取文件夹下所有xlsx
for 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为56
wb.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,sys
def 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 os
def 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 os
work_space_path = os.getcwd() + '\DMS_WorkSpace' # Work Space Name
def 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):改变工作目录到dirname
os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.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 time
import os
def 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:BasicCurriculumInfo
import math
class 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 statement
def __init__(self, workbook_obj):
self.__defaultWorkbook = workbook_obj
self.__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 func
return self.__curriculumArea
def get_duration(self, week, num):
week_list_all = []
curriculum_string = self.__curriculumArea[num - 1][week - 1].value
if curriculum_string == ' ':
return -1
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 += chars
week_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 += chars
week_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 += chars
week_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_all
def __find_all_subs(self, sub, s):
self.__static_to_class_m = 0
index_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
else:
return -1
def __str_to_int(self, o_str):
self.__static_to_class_m = 0
char_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 = 0
integer = 0
while bit != 0:
integer += int_list[local_iter] * math.pow(10, bit - 1)
local_iter += 1
bit -= 1
return int(integer)
def __curriculum_expansion(self, o_str_list):
self.__static_to_class_m = 0
u_list = []
u_start = 0
u_end = 0
t_list = []
for step_len in o_str_list:
if step_len == '':
continue
if '-' 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_list
def __reconnect_lists(self, o_list, t_list):
self.__static_to_class_m = 0
o_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:BasicCurriculumInfo
import openpyxl as vpa
import re
class StudentSheetInfo:
__defaultWorkbook = 0
__defaultWorksheet = 0
__basicTitle = 0
__infoTitle = 0
def __init__(self, workbook_obj):
self.__defaultWorkbook = workbook_obj
self.__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 = i
break
return 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 = i
break
return 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 = i
break
return 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:BasicCurriculumInfo
import math
class 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 statement
def __init__(self, workbook_obj):
self.__defaultWorkbook = workbook_obj
self.__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 function
return self.__curriculumArea
def get_duration(self, week, num):
week_list_all = []
curriculum_string = self.__curriculumArea[num - 1][week - 1].value
if curriculum_string == ' ':
return -1
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 += chars
week_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 += chars
week_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 += chars
week_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_all
def __find_all_subs(self, sub, s): # find all substring in string
self.__static_to_class_m = 0
index_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 index
else:
return -1 # return -1 if nothing have found
def __str_to_int(self, o_str): # convert a string type number to int
self.__static_to_class_m = 0
char_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 = 0
integer = 0
while bit != 0:
integer += int_list[local_iter] * math.pow(10, bit - 1)
local_iter += 1
bit -= 1
return int(integer)
def __curriculum_expansion(self, o_str_list): # get a string with ',' and expand it
self.__static_to_class_m = 0
t_list = []
for step_len in o_str_list:
if step_len == '':
continue
if '-' 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_list
def 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 bound
for chapter in range(1, 6 + 1): # 6 lesson a day and a bound
layout.append(self.list_to_binary(self.get_duration(week, chapter)))
return layout
@staticmethod
def list_to_binary(o_list):
m_binary = 0
if o_list == -1: # runtime datatype double check, (Customized)
return -1
for it in o_list:
m_binary += 2 ** it
return m_binary
@staticmethod
def binary_to_list(o_bin):
const_bit = 0b1
m_list = []
for it in range(0, 20):
ret = o_bin & const_bit # get last bit
if ret == 1:
m_list.append(it)
o_bin = o_bin >> 1
return m_list
"""
Excel cannot convert a list data type to a table data type.
However, the list is not repeated, so I can use binary
distribution 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 transfer
this list into a number which is 0b101100
0 b 1 0 1 1 0 0
^ ^ ^
5 3 2
and this number is 44 (int)
"""
# -*- coding: utf-8 -*-
# Filename:BasicCurriculumInfo
"""
class provides basic information of curriculum table
most of method may not used in actual practice
the variable 'end_mark' is local variable, ignore
some warnings below:
"Local variable 'end_mark' might be referenced before assignment"
DO NOT ADD GLOBAL STATEMENTS
"""
import re
class StudentSheetInfo:
__defaultWorkbook = 0
__defaultWorksheet = 0
__basicTitle = 0
__infoTitle = 0
def __init__(self, workbook_obj):
self.__defaultWorkbook = workbook_obj
self.__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 = i
break
return 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 = i
break
return 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 = i
break
return 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:]