2013-08-07 34 views
1

代碼是從目錄中讀取xls文件,將其轉換爲csv文件並將其複製到另一個目錄。python shutil:只複製文件的一部分

filePath = os.path.join('.', 'attachments') 
filePaths = [f for f in os.listdir(filePath) if os.path.isfile(os.path.join(filePath, f)) and f.endswith('.xls')] 

for f in filePaths: 
    wb = xlrd.open_workbook(os.path.join(filePath, f)) 
    sheet = wb.sheet_by_index(0) 
    filename = f + '.csv' 
    fp = open(os.path.join(filePath, filename), 'wb') 
    wr = csv.writer(fp, quoting=csv.QUOTE_ALL) 
    for rownum in xrange(sheet.nrows): 
     wr.writerow(sheet.row_values(rownum)) 
    fp.close 

    shutil.copy(os.path.join('.', 'attachments', filename), new_directory) 

結果是: XLS文件被成功地轉換爲csv文件,但在new_directory,複製的文件只包含CSV文件的一部分。

例如,原始csv文件有30行,但在複製的文件中只有17行。任何想法爲什麼會發生?

回答

3

這是你的問題:

fp.close 

您需要呼叫close方法,而不只是引用它作爲一種方法。所以:

fp.close() 

然而,它會讓你的生活更容易,如果你使用with語句,而不是試圖找出其中明確close一切:

with open(os.path.join(filePath, filename), 'wb') as fp: 
    wr = csv.writer(fp, quoting=csv.QUOTE_ALL) 
    for rownum in xrange(sheet.nrows): 
     wr.writerow(sheet.row_values(rownum)) 
+0

嗯,多麼愚蠢的錯誤,我已經做。非常感謝您的快速回答! – Cacheing

+0

但我仍然不明白爲什麼我沒有通過使用'fp.close'來得到一個錯誤。 'fp.close'和'fp.close()'有什麼區別? – Cacheing

+2

'fp.close'只是獲得對函數的引用。它不是一個錯誤 - 你可以將這個引用存儲在一個變量中,稍後調用它,將它傳遞給另一個最終會調用它的函數等。'()'是*調用該函數的操作,即執行它。所以一個普通的函數調用實際上有兩個部分:1)獲取函數的引用(你給它的名字,就像獲得對其他對象的引用一樣),2)調用它。 – kindall