Python反斜杠错误

时间:2013-07-25 19:00:53

标签: python xlrd

我在python中创建一个程序,它将复制excel文件,根据其内容重命名,然后将它们保存在不同的文件夹中。

我在代码中遇到了反斜杠的问题。关于如何使这项工作的任何想法?

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'

1 个答案:

答案 0 :(得分:1)

您的文件名中不能包含正斜杠,它似乎是代码中错误的来源(我假设您不希望每个新文件有多个新目录)。

尝试:

datenew = "00-00-00"
相关问题