Excelファイルをコピーし、内容に応じて名前を変更し、別のフォルダーに保存するプログラムをPythonで作成しています。
ただし、コード内のバックスラッシュに問題があります。これを機能させる方法についてのアイデアはありますか?
import os
import os.path
import csv
import xlrd
import datetime
import glob
import shutil
def newfilename(name):
book = xlrd.open_workbook(name)
sheet = book.sheet_by_index(0)
name = sheet.cell(6,6).value
name = name[:10]
pn = sheet.cell(6,1).value
date = sheet.cell(4,0).value
try:
datenew = datetime.datetime(*xlrd.xldate_as_tuple(date, book.datemode))
except:
datenew = "00/00/00"
print(datenew)
datenew = str(datenew)
print(datenew)
datenew = datenew[:10]
newpn = ""
for i in pn:
try:
rand = int(i)
newpn = newpn + str(rand)
except:
pass
return str(newpn+"-"+str(name)+"-PackagingForm-"+datenew)
def excelwriter(old_file_path,new_file_path):
for subfolder_name in os.listdir(old_file_path):
print(subfolder_name)
subfolder_path = os.path.join(old_file_path,subfolder_name)
print(subfolder_path)
print(os.listdir(os.path.join(old_file_path,subfolder_path)))
for file_name in os.listdir(os.path.join(old_file_path,subfolder_path)):
file_path = os.path.join(subfolder_path,file_name)
print("file path" +file_path)
try:
new_file_name = newfilename(file_path)
except:
new_file_name = "NEW" + file_name
new_file_path = os.path.join(new_file_path,subfolder_name,new_file_name)
new_file_path.replace(r"\\","/")
print(str(new_file_path))
print(str(new_file_path)+".xlsx")
if file_name[-4:]=="xlsx":
os.rename(str(file_path),str(new_file_path)+".xlsx")
elif file_name[-3:]=="xls":
os.rename(str(file_path),str(new_file_path)+".xls")
elif file_name[-3:]=="pdf":
os.rename(str(file_path),str(new_file_path)+".pdf")
else:
pass
ここから、次のエラーが表示されます。
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
excelwriter(r'C:\Users\harridr3\Desktop\New Test',r'C:\Users\harridr3\Desktop\New folder')
File "C:\Users\harridr3\Desktop\python testing\renaming.py", line 52, in excelwriter
os.rename(str(file_path),str(new_file_path)+".xlsx")
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\harridr3\\Desktop\\New folder\\ABL Lights\\2344327-ABL Lights-PackagingForm-00/00/00.xlsx'