#创建txt文件
name=createTxt()
#获取全部的txt文件
#fileNameList = getFileName(path)
#调用批处理函数
#docToDocx(fileNameList)
#删除原txt文件
# for i in range(1, 10):
# os.remove('E:\%s\%s.txt' % (name, i))
#写入数据
writeData(name)
上面这段代码单独调用,程序就没有出现Traceback (most recent call last)的问题,如果全部一起调用,就出现这个问题,不知道是哪里出了问题,请广大的前辈大佬停下脚步,帮忙看看代码哪里出了问题。
import os
import win32com.client as wc
word = wc.Dispatch('Word.Application')
# 将docx文件保存的路径
docxPath = 'E:\page'
# doc文件路径
path = "E:\page"
def getFileName(path):
filesList = []
for root, dirs, files in os.walk(path):
isExists = os.path.exists(docxPath)
# 新建docx文件夹
if not isExists:
os.makedirs(docxPath)
for file in files:
# 判断尾缀是不是txt
suffix = file.split('.')[1]
if suffix == 'txt':
filesList.append(file)
print(filesList)
return filesList
def docToDocx(fileNameList):
try:
for fileName in fileNameList:
print("开始处理 -----------------------------文件名:" + fileName)
doc = word.Documents.Open(path + '\\' + fileName)
# [:-4]的意思是选这个字符串从开始到最后倒数第4位(不含)
docxNamePath = docxPath + '\\' + fileName[:-4] + '.docx'
print('转换完成!-----------------------------' + docxNamePath)
doc.SaveAs(docxNamePath, 12, False, "", True, "", False, False, False, False)
finally:
# 一定要记得关闭docx,否则会出现文件占用
doc.Close()
def createTxt():
while (1):
name = input("请输入目录名:");
r = os.path.exists('E:\%s' % name)
if r is True:
print("目录名已存在!")
a = input("是否返回上一层?1/0")
if a is '1':
continue
else:
break
else:
os.mkdir('E:\%s' % name)
for i in range(1, 10):
f = open('E:\%s\%s.txt' % (name, i), 'w+', encoding='utf-8')
print("创建 文件名:%s.txt" %i)
f.close()
break
return name
def writeData(name):
for j in range(1, 10):
f = open(r'E:\%s\%s.docx' % (name,j), 'w+', encoding='utf-8')
f.write("亲爱的同学,欢迎回来。")
print("数据写入成功!----------------%s.docx" % j)
f.close()
try:
#创建txt文件
name=createTxt()
#获取全部的txt文件
fileNameList = getFileName(path)
#调用批处理函数
docToDocx(fileNameList)
#删除原txt文件
for i in range(1, 10):
os.remove('E:\%s\%s.txt' % (name, i))
#写入数据
writeData(name)
finally:
word.Quit()
运行结果及报错内容
Traceback (most recent call last):
File "D:/python/projects/firstWork/**16.py", line 93, in <module>
writeData(name)
File "D:/python/projects/firstWork/作业16.py", line 77, in writeData
f = open(r'E:\%s\%s.docx' % (name,j), 'w+', encoding='utf-8')
PermissionError: [Errno 13] Permission denied: 'E:\\page\\1.docx'