2015-04-24 128 views
0

我已經能夠編寫批處理文件來查找文件並將文件路徑放入CSV中。我一直無法弄清楚如何從CSV中讀取文件位置,然後使用python將文件移動到具有相同文件夾結構的不同存儲設備。這是我想要做的。從CSV讀取文件名,然後將文件複製到不同的目錄

我希望我有一些代碼給你看,但沒有一個工作。

+0

退房'shutil.copy' –

+3

使用閱讀文件位置[csv](https://docs.python.org/3/library/csv.html#module-csv)模塊。使用[os.path](https://docs.python.org/3/library/os.path.html#module-os.path)將每個文件路徑下拉至文件名,然後再次使用它加入目標文件夾路徑指向文件名。此時,您所要做的就是將文件從原始位置複製到目標位置。 – martineau

+3

即使它不能正常工作,發佈迄今爲止生成的代碼以及它需要的輸入(這裏是CSV文件)總是很好的。也發佈其目前的產出,以及這與您的期望產出有何不同。 (在你的情況下,哪些文件被移動。) – dbliss

回答

0

這是一個快速和骯髒的解決方案。 (我沒有測試它,但情況因人而異!)

import csv 
import os 
import shutil 
import sys 


def main(argv): 
    # TODO: this should do some error checking or maybe use optparse 
    csv_file, existing_path_prefix, new_path_prefix = argv[1:] 

    with open(csv_file, 'rb') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     # Assuming the column in the CSV file we want is the first one 
     filename = row[0] 

     if filename.startswith(existing_path_prefix): 
     filename = filename[len(existing_path_prefix):] 

     new_filename = os.path.join(new_path_prefix, filename) 

     print ('Copying %s to %s...' % filename, new_filename), 
     shutil.copy(filename, new_filename) 
     print 'done.' 
    print 'All done!' 


if __name__ == '__main__': 
    main(sys.argv) 
0

添加到丹尼爾的職位,因爲他沒有提醒他還沒有測試它:),我想你會需要做一些小的變化。基本上,我認爲在建議的代碼中的問題是filename被認爲是完整的路徑。但是,如果您爲new_filename找到os.path.join命令,則會產生問題,因爲您正在向完整路徑和名稱添加新路徑。

我會建議在您的csv中包含filepathfilename以使代碼運行。這些變化出現時,我TESTD它的工作,雖然我沒有爲函數運行(我用print()報表的Python 3.4語法):

with open(csv_file, 'rb') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     # Assuming the columns in the CSV file we want are the first two // Changed 
     filename = row[0] 
     filepath = row[1] #Changed 

    '''Changed: I skipped over this next part, didn't need it, but should be 
    easy enough to figure out 
    if filename.startswith(existing_path_prefix): 
     filename = filename[len(existing_path_prefix):] 
    ''' 

    new_filename = os.path.join(new_path_prefix, filename) 

    print ('Copying %s to %s...' % filepath, new_filename) #Changed 
    shutil.copy(filepath, new_filename) #Changed 
    print 'done.' 
print 'All done!' 
相關問題