import os
import win32com.client as win32
import shutil
#####第一步先降原文件夹中的xlsx文件直接拷贝至bak文件夹中
file = []
path = os.getcwd() #转换前程序所在文件目录
path_bak = os.getcwd() + r'/bak/'
pathdir = os.listdir(path)
for s in pathdir:
newdir = os.path.join(path,s)
if os.path.isfile(newdir):
os.chdir(path_bak)
pathdir_bak = os.listdir(path_bak)
print(pathdir_bak)
if os.path.splitext(newdir)[1] == ".xls" :
t = os.path.split(s)[1] + r'x'
if os.path.exists(t):
print(os.path.exists(os.path.split(s)[1]))
break
else:
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(newdir)
print(newdir)
path_dir = os.path.split(newdir)[0]
path_file = os.path.split(newdir)[1]
print(path_dir)
print(path_file)
wb.SaveAs(path_dir + '/bak/' + path_file + 'x', FileFormat=51) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
elif os.path.splitext(newdir)[1] == ".xlsx" :
file.append(newdir)
elif os.path.isdir(newdir):
continue
for i in range(len(file)):
pcm_file = file[i]
path_0 = os.path.split(file[i])[0]
path_1 = os.path.split(file[i])[1]
oldname = path_0 + '/' + path_1
newname = path_0 + r'/bak/' + path_1
shutil.copyfile(oldname,newname)
#####第二步将文件目录切换至bak文件夹中,
os.chdir(path_bak)
pathdir_bak = os.listdir(path_bak)
#print(pathdir_bak)
'''
############转换前的文件夹
filelist_trans = []
path_trans = os.getcwd() #转换前程序所在文件目录
print(path_trans)
pathlist_trans = os.listdir(path_trans)
print(pathlist_trans)
path_same_rear = 'bak'
path_same = path_trans + '/' + path_same_rear
############需要同步的文件夹
filelist_same = []
path_same_head = os.getcwd()
path_same_rear = 'bak'
path_same = path_same_head + '/' + path_same_rear
print(path_same)
os.chdir(path_same)
pathlist_same = os.listdir(path_same)
for trans in pathlist_trans:
filelist_trans = os.path.join(path_trans, trans) # 将文件名加入到当前文件路径后面
print(filelist_trans)
if os.path.isfile(filelist_trans):
if os.path.splitext(filelist_trans)[1] == ".xlsx":
print(os.path.splitext(filelist_trans))
# shutil.copyfile(os.path.splitext(filelist_trans), path_same)
# if os.path.splitext(filelist_trans)[1] == ".xls" and : # 如果文件是".xls"后缀的
filelist_same = []
path_same_head = os.getcwd()
path_same_rear = 'bak'
path_same = path_same_head + '/' + path_same_rear
os.chdir(path_same)
myfile = '2.xlsx'
if os.path.exists(myfile):
print(myfile)
'''
#02终于成功解决xls xlsx转换、xls xlsx文件复制,重名跳过
最新推荐文章于 2024-05-30 15:46:54 发布