這裏是代碼:
import xlsxwriter
from xlrd import open_workbook
import os.path
import shutil
def search(fname,url):
global rw
global cpy_file
counter=0
dest_folder="C:\\Users\\Public\\Downloads\\File_Search\\output"
for root, dirs, files in os.walk(url, topdown=False):
for name in files:
if fname in name:
path= os.path.join(root, name)
cl=0
worksheet.write(rw,cl,name+":")
cl=1
worksheet.write_url(rw,cl,path)
rw=rw+1
counter=1
if cpy_file == "Y":
shutil.copy(path, dest_folder)
break
else:
continue
break
if counter == 0:
cl=0
worksheet.write(rw,cl,fname)
cl=1
worksheet.write(rw,cl,"Not Available")
rw=rw+1
if __name__ == "__main__":
print "Please make sure you have prepared the excel list"
url= str(raw_input("Enter the Search Path: "))
cpy_file= str(raw_input("Do you want to copy the files, Y/N: "))
dest_folder="C:\\Users\\Public\\Downloads\\File_Search\\output"
wb = open_workbook('C:\\Users\\Public\\Downloads\\File_Search\\Input.xlsx')
sh = wb.sheet_by_index(0)
rw=0
workbook = xlsxwriter.Workbook('C:\\Users\\Public\\Downloads\\File_Search\\output.xlsx')
worksheet = workbook.add_worksheet()
print "Searching...Please Wait..."
for row in range(sh.nrows):
fname= sh.cell(row,0).value
search(fname,url)
print "Search Completed....."
print "Find the file path 'C:\\Users\\Public\\Downloads\\File_Search\\output.xlsx'"
if cpy_file == "Y":
print "Files copied to 'C:\\Users\\Public\\Downloads\\File_Search\\output'"
workbook.close()
錯誤我得到如果搜索到的文件不存在於位置:
Traceback (most recent call last):
File "C:\Users\Public\Downloads\File_Search\search.py", line 61, in <module>
search(fname,url)
File "C:\Users\Public\Downloads\File_Search\search.py", line 26, in search
if fname in name:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 25: ordinal not in
range(128)
Exception Exception: Exception('Exception caught in workbook destructor. Explicit close() may be
required for workbook.',) in <bound method Workbook.__del__ o
<xlsxwriter.workbook.Workbook object at 0x025788D0>> ignored
您能否提供一個[最小示例](http:// stackoverflo w.com/help/mcve)複製了這個問題?在嘗試寫入文件之前,爲什麼不檢查文件是否存在? – jonrsharpe 2014-10-03 10:19:37